题目:
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:
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?
解题思路
用一个HashMap去记录从开始到第n个元素时的和以及对应最多可以向前包含到第几个元素,当出现相同的key时,取比较靠前的元素,因为这道题是取尽量长的长度
Corner Case::当array为空或者没有元素时,直接返回0。
Case 1:当map中没有prefix sum时,在map中添加prefix sum以及对应的元素个数(i+1)。
Case 2:当map中有sum-k的值时,代表array中含有部分等于目标值,查看并更新最大长度。
k
|<------------>|<-------------------------->|
sum
Time Complexity: O(n)
Space Complexity: O(n)
public class Solution {
public int maxSubArrayLen(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
int max = 0;
Map<Integer, Integer> map = new HashMap<>();
int sum = 0;
map.put(0, 0);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (!map.containsKey(sum)) {
map.put(sum, i+1);
}
if (map.containsKey(sum-k)) {
max = Math.max(max, i-map.get(sum-k)+1);
}
}
return max;
}
}