Maximum Size Subarray Sum Equals k
Given an arraynumsand a target valuek, find the maximum length of a subarray that sums tok. If there isn't one, return 0 instead.
Note:
The sum of the entire num s array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Givennums=[1, -1, 5, -2, 3]
,k=3
,
return4
. (because the subarray[1, -1, 5, -2]
sums to 3 and is the longest)
Example 2:
Givennums=[-2, -1, 2, 1]
,k=1
,
return2
. (because the subarray[-1, 2]
sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?
题意:给定一个数组nums,求和为k最大连续子数组长度
图解
分析
代码
class Solution {
public int maxSubArrayLen(int[] nums, int k) {
if (nums==null || nums.length==0) return 0;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, -1);
int sum = 0;
int maxLen = Integer.MIN_VALUE;
for (int i=0; i<nums.length; i++) {
sum += nums[i];
if (!map.containsKey(sum)) {
map.put(sum, i);
}
if (map.containsKey(sum-k)) {
int index = map.get(sum-k);
maxLen = Math.max(maxLen, i-index);
}
}
return maxLen==Integer.MIN_VALUE? 0 : maxLen;
}
}