325. Maximum Size Subarray Sum Equals k
Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn’t one, return 0 instead.
Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
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:
Input: nums = [-2, -1, 2, 1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.
Hint:
- Try to compute a sum of a subsequence very fast, i.e in O(1) … Think of prefix sum array.
- Given S[i] a partial sum that starts at position 0 and ends at i, what can S[i - k] tell you ?
- Use HashMap + prefix sum array
Follow Up:
Can you do it in O(n) time?
方法0:
方法1: hash + prefix
思路:
根据hint,可以套用560. Subarray Sum Equals K中的方法。从前往后遍历一遍,对于每一个数字nums[i],记录前缀和prefix[i],并且向前查找hash中有没有prefix[i] - k。这里需要用到的是前面prefix[i] - k 所对应的entry,并且只用取最小的一个,因为遍历顺序的关系,累计长度一定不会超过前面的位置。那么需要的数据结构就是unordered_map<int, int>。 如果该entry已经存在,可以跳过,不存在则记录下来,也就是第一次出现的位置。
易错点
- 不管sum是否已经存在在hash中,result = max(result, i - prefix[sum - k])都应该参与计算结果。当前位置不加入hash只是因为它不会再成为后面的起点,但是有可能作为终点和前面组成最长subarray。不要直接跳过。
- 还要检查prefix[sum - k] 是否存在,没有这个检查不会报key error,只会返回0
- 两个boundary检查只用一个就行
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
unordered_map<int, int> prefix;
// boundary 1
// prefix[0] = -1;
int result = 0;
int sum = 0;
for (int i = 0; i < nums.size(); i ++){
sum += nums[i];
// boundary 2
if (sum == k) result = i + 1;
else if (prefix.count(sum - k)){
result = max(result, i - prefix[sum - k] );
}
if (prefix.count(sum) == 0 ){
prefix[sum] = i;
}
}
return result;
}
};
// [1,-1,5,-2,3]
// k = 3
// sum = 3
// result = 4
// i = 3
// prefix = {0: 0, 1: 0, 5: 2, 3: 3, 6: 4}