325. Maximum Size Subarray Sum Equals k

325. Maximum Size Subarray Sum Equals k

Description

Difficulty: Medium

Related Topics: Array, Hash Table, Prefix Sum

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.

Example 1:

1
2
3
Input: nums = [1,-1,5,-2,3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Example 2:

1
2
3
Input: nums = [-2,-1,2,1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

Constraints:

  • 1 <= nums.length <= 2 * 105
  • -104 <= nums[i] <= 104
  • -109 <= k <= 109

Hints/Notes

  • preSum + map

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        int size = nums.size();
        vector<intpreSum(size + 10);
        for (int i = 0; i < size; i++) {
            preSum[i + 1] = preSum[i] + nums[i];
        }
        map<longint> m;
        int res = 0;
        for (int i = 0; i <= size; i++) {
            if (m.count((long)preSum[i] - k)) {
                res = max(res, i - m[preSum[i] - k]);
            }
            if (!m.count(preSum[i])) {
                m[preSum[i]] = i;
            }
        }
        return res;
    }
};