Skip to content

Instantly share code, notes, and snippets.

@gauravkr0071
Created August 5, 2021 14:22
Show Gist options
  • Save gauravkr0071/1bad4286e8aaa506b7110b333cc6fee4 to your computer and use it in GitHub Desktop.
Save gauravkr0071/1bad4286e8aaa506b7110b333cc6fee4 to your computer and use it in GitHub Desktop.
longest subarray with k sum
/*
find the longest subbary with sum k,
k can also be zero, return -1 if no array with sum k is present
*/
unordered_map<int, int>u;
int len=INT_MIN;
for(int i=0;i<nums.size();i++)
{
temp+=nums[i];
if(temp==k) len=i+1;
if(u.find(temp-k)!=u.end())
len=max(len,i-u[temp-need]);
if(u.find(temp)==u.end())
u[temp]=i;
}
if(len==INT_MIN) return -1;
else return len;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment