Created
August 5, 2021 14:22
-
-
Save gauravkr0071/1bad4286e8aaa506b7110b333cc6fee4 to your computer and use it in GitHub Desktop.
longest subarray with k sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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