Maximum Size Subarray Sum Equals k
Problem:
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.
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Given nums =
return
[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 =
return
[-2, -1, 2, 1]
, k = 1
,return
2
. (because the subarray [-1, 2]
sums to 1 and is the longest)
Analysis:
Typical presum and hashmap problem. Note that if we found current sum in hashmap don't update the index, since the existing one is further.
Solution:
class Solution { public int maxSubArrayLen(int[] nums, int k) { int max = 0; if (nums == null || nums.length == 0) return 0; Map<Integer, Integer> preSum = new HashMap<>(); int sum = 0; preSum.put(0, -1); for (int i = 0; i < nums.length; i++) { sum += nums[i]; if(preSum.containsKey(sum - k)) { max = Math.max(max, i - preSum.get(sum - k)); } if (!preSum.containsKey(sum)) { preSum.put(sum, i); } } return max; } }
评论
发表评论