[LeetCode] Maximum Size Subarray Sum Equals k

325. Maximum Size Subarray Sum Equals k

Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
//value, index;
unordered_map<int, int> lookup{{0,-1}};
int sum = 0, res = 0;
for(int i = 0; i < nums.size(); i++) {
sum += nums[i];
if(lookup.find(sum - k) != lookup.end()) {
res = max(res, i - lookup[sum - k]);
}
if(lookup.find(sum) == lookup.end())
lookup[sum] = i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/maximum-size-subarray-sum-equals-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.