Loading content...
Created On: December 14, 2023
Problem Statement (Coding NInjas)
int longestSubarrayWithSumK(vector<int> a, long long k) {
int l = 0, r = 0;
long long curr_sum = a[0], curr_len = 0, max_len = 0;
//traverse the array
while(r < a.size()){
//if current_sum > k then
while(curr_sum > k && l <= r){
//compress the window
curr_sum -= a[l];
l++;
}
//compute the current_length
curr_len = r-l+1;
//if you find any subarray with sum k
//update the max_len if the subarray's length is
//greater than the max_len
if(curr_sum == k)
max_len = max(curr_len, max_len);
r++;
//else untill the we reach to the end
//compute the current sum
if(r < a.size())
curr_sum += a[r];
}
return max_len;
}int longestSubarrayWithSumK(vector<int> a, long long k) {
long long curr_sum = 0;
int max_len = 0;
//declare a map to store the current_sum at ith idx
unordered_map<long long, int> map;
for(int i=0; i<a.size(); i++){
//traverse the array and compute the current sum
curr_sum += a[i];
//if current_sum == k and i+1 > max_len
//upddate max_len
if(curr_sum == k)
max_len = max(i+1, max_len);
//if you find the cummulative sum in the above map
if(map.find(curr_sum - k) != map.end()){
//check if the lenght of that subarray is
//greater than max_len then update max_len
int curr_len = i - map[curr_sum - k];
max_len = max(curr_len, max_len);
}
//else if you don't find the sum in the map
//store it with the current_idx in the map
if(map.find(curr_sum) == map.end())
map[curr_sum] = i;
}
return max_len;
}