Reference: LeetCode
Difficulty: Medium

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.

Example:

1
2
3
4
5
6
7
Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

Input: nums = [-2, -1, 2, 1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.

Follow up: Can you do it in $O(N)$ time?

Analysis

Brute-Force

Calculate sum for each possible subarray. The sum can be accumulated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int maxSubArrayLen(int[] nums, int k) {
// assume nums is not null
int len = nums.length;
int maxSize = 0;

for (int i = 0; i < len; ++i) {
int sum = 0;
for (int j = i; j < len; ++j) {
// subarray nums[i, j]
sum += nums[j];
if (sum == k) {
maxSize = Math.max(maxSize, j - i + 1);
}
}
}

return maxSize;
}

Time: $O(N^2)$
Space: $O(1)$

Hash Map

Based on the idea in 560. Subarray Sum Equals K, we need to make some modifications.

  • The hash map stores pairs <prefixSum, index>.
  • Size of the subarray is i - map.get(sum - k). There is no +1 required since the leftmost element is not included.
  • The map should be initialized with <0, -1> based on the second point above.
  • We only store the earliest index of a specific prefix sum, although there are multiple indices. The earliest index gives us a larger size.
1
2
3
4
5
[1, -1, 5, -2, 3], k = 3
Output: 4

[-2, -1, 2, 1], k = 1
Output: 2

Go through these two examples to have a better understanding.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public int maxSubArrayLen(int[] nums, int k) {
// assume nums is not null
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>(); // <prefixSum, index>

map.put(0, -1);
int sum = 0;
int maxSize = 0;
for (int i = 0; i < n; ++i) {
sum += nums[i];

if (map.containsKey(sum - k)) {
int size = i - map.get(sum - k);
maxSize = Math.max(maxSize, size);
}
// only stores the earliest index
if (!map.containsKey(sum)) {
map.put(sum, i);
}
}

return maxSize;
}

Time: $O(N)$
Space: $O(N)$