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.
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)
Follow Up:
Can you do it in O(n) time?
Solution:Can you do it in O(n) time?
The idea of the problem is to check where there is a range from i to j, inclusive, so that its sum equals to k, and the length of the range is the maximum.
So we can naturally think of this question as a range summary problem, and we need to calculate the prefix sum of the array first. So the sum(i, j) = presum[j] - presum[i - 1] = k
In order to achieve the O(n) time, we can leverage the same idea of the "Two Sum" problem by using a hash map. So we store the presum[i - 1] + k into the map, and check if presum[j] is in the map for each iteration. Note that we can do this in one-pass of loop iteration because for each j, i - 1 must be in the position above j.
Code (Java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public class Solution { public int maxSubArrayLen( int [] nums, int k) { if (nums == null || nums.length == 0 ) { return 0 ; } // step 1: calculate the prefix sum for all numbers of the nums array int n = nums.length; int [] preSum = new int [n + 1 ]; int sum = 0 ; for ( int i = 0 ; i < nums.length; i++) { sum += nums[i]; preSum[i + 1 ] = sum; } // step 2: put the preSum + target into a map int max = 0 ; Map<Integer, Integer> map = new HashMap<>(); for ( int j = 0 ; j < preSum.length; j++) { if (map.containsKey(preSum[j])) { max = Math.max(max, j - map.get(preSum[j])); } if (!map.containsKey(preSum[j] + k)) { map.put(preSum[j] + k, j); } } return max; } } |
No comments:
Post a Comment