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.
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Given nums = [1, -1, 5, -2, 3], k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
Example 2:
Given nums = [-2, -1, 2, 1], k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?
没有
没有思路,
【1,-1,5,-2,3】k = 3
prefixSum 【1, 0, 5, 3, 6】
if(map.containsKey(prefixSum - k)) {
//update the result
res = Math.max\(res, I - map.get\(prefixSum - k\)\);
}
//if it does not have this prefixSum in the map yet, save it
//problem is you have to set
//
Map.put(0,-1);
At the very beginning so that when Map get
Input:
[1,-1,5,-2,3]
3
Output:
2
Expected:
4
class Solution {
public int maxSubArrayLen(int[] nums, int k) {
//[-2, -1, 2, 1]
//-2 -3 -1 0
// k = 1
if (nums == null || nums.length == 0) {
return 0;
}
int ans = 0;
int prefixSum = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
for (int i = 0; i < nums.length; i++) {
prefixSum += nums[i];
if (map.containsKey(prefixSum - k)) {
ans = Math.max(ans, i - map.get(prefixSum - k));
}
if (!map.containsKey(prefixSum)) {
map.put(prefixSum, i);
}
}
return ans;
}
}