Maximum Size Subarray Sum Equals K in C++
Suppose we have an array called nums and a target value k, we have to find the maximum length of a subarray that sums to k. If there is not present any, return 0 instead.
So, if the input is like nums = [1, -1, 5, -2, 3], k = 3, then the output will be 4, as the subarray [1, - 1, 5, -2] sums to 3 and is the longest.
To solve this, we will follow these steps −
ret := 0
Define one map m
n := size of nums
temp := 0, m[0] := -1
for initialize i := 0, when i < n, update (increase i by 1), do −
temp := temp + nums[i]
if (temp - k) is in m, then −
ret := maximum of ret and i - m[temp - k]
if temp is not in m, then −
m[temp] := i
return ret
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int maxSubArrayLen(vector<int<& nums, int k) { int ret = 0; unordered_map <int, int> m; int n = nums.size(); int temp = 0; m[0] = -1; for(int i = 0; i < n; i++){ temp += nums[i]; if(m.count(temp - k)){ ret = max(ret, i - m[temp - k]); } if(!m.count(temp)){ m[temp] = i; } } return ret; } }; main(){ Solution ob; vector<int< v = {1,-1,5,-2,3}; cout << (ob.maxSubArrayLen(v, 3)); }
Input
[1,-1,5,-2,3], 3
Output
4
Advertisements