Note, since we scan from 0 to n, if sum[i] == k, the max length so far must be i+1. Also to avoid duplicates, we only save (sum, i) when this pair isn't existing in hash table. Why we don't have to save the pair (sum, j) later? Because we want to get the maximum size, the first pair guarantees it.
1: class Solution {
2: public:
3: int maxSubArrayLen(vector<int>& nums, int k) {
4: unordered_map<int, int> mp;
5: int sum = 0, maxLen = 0;
6: for (int i = 0; i < nums.size(); i++) {
7: sum += nums[i];
8: if (k == sum) maxLen = i+1;
9: else if (mp.find(sum-k) != mp.end()) maxLen = max(maxLen, i-mp[sum-k]);
10: if (mp.find(sum) == mp.end()) mp[sum] = i;
11: }
12: return maxLen;
13: }
14: };
No comments:
Post a Comment