Maximum Size Subarray Sum Equals k
Medium
Topics
Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is no such subarray, return 0.
Example 1
The braced run sums to 3 and is the longest that does, length 4.
Cells are the array values; the small numbers underneath are indices.
Input: nums = [1,-1,5,-2,3], k = 3 Output: 4 Explanation: The subarray [1,-1,5,-2] sums to 3 and has length 4.
Example 2
Input: nums = [-2,-1,2,1], k = 1 Output: 2 Explanation: The subarray [-1,2] sums to 1.
Example 3
No block sums to 100, so the answer is
0.Input: nums = [1,2,3], k = 100 Output: 0
Constraints
- 1 <= nums.length <= 2 * 10^5
- -10^4 <= nums[i] <= 10^4
- -2^31 <= k <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
A subarray sums to k exactly when the prefix before it and the prefix after it differ by k. So for each prefix, ask whether the value prefix - k has been seen earlier - and because you want the longest such subarray, remember the earliest index at which each prefix value appeared.
Approach
- Keep a running prefix sum and a map from prefix value to its first index. Seed with
{0: -1}. - At index i, if
prefix - kis in the map, the subarray fromfirst[prefix - k] + 1to i sums to k - a candidate of lengthi - first[prefix - k]. - Insert the current prefix only if it is absent, keeping the earliest occurrence.
- Return the largest candidate, or 0 if none was found.
class Solution:
def maxSubArrayLen(self, nums, k):
first = {0: -1}
total = 0
best = 0
for i, v in enumerate(nums):
total += v
if total - k in first:
best = max(best, i - first[total - k])
if total not in first:
first[total] = i
return bestDry Run
nums = [1, -1, 5, -2, 3], k = 3
Same transformation as contiguous-array: a subarray sums to k exactly when two
prefix sums differ by k, so look up `running - k`.
i=0 v= 1 running 1 record prefix 1 at 0
i=1 v=-1 running 0 0 is already recorded at -1
i=2 v= 5 running 5 record prefix 5 at 2
i=3 v=-2 running 3 running-k = 0, seen at -1 -> span 4 best 4
record prefix 3 at 3
i=4 v= 3 running 6 running-k = 3, seen at 3 -> span 1 best 4
record prefix 6 at 4
answer 4 -- the subarray 1 -1 5 -2 at indices 0..3
Note i=1: the running sum returns to 0, which is already in the map at -1, and
nothing is recorded. Keeping the FIRST index is what maximises every later span,
and it is the only difference from the count-the-subarrays variant, which stores
a frequency instead. Using the wrong one is the classic mix-up between these two
problems.
The {0: -1} sentinel again makes a prefix-length subarray measurable: the answer
here is found against it.
Negative values are the reason a prefix map is required rather than a sliding
window -- the running sum goes down as well as up, so there is no shrink
condition to exploit.Complexity
- Time — O(n) — one pass.
- Space — O(n) for the prefix map.
Common Pitfalls
- This is the length variant, so store the first index per prefix. Subarray Sum Equals K stores a count instead - using the wrong one is the classic mix-up.
- Querying the map before inserting the current prefix reads like a correctness requirement and is not one, which is worth knowing before you hunt a bug there. Swapping the two statements changes no answer across 40000 random inputs: when k is 0 the self-match scores a span of 0, and
maxnever lowers the best. - Negative numbers rule out a sliding window entirely - do not try to shrink from the left.
- Prefix sums can exceed 32 bits at the stated limits; use a 64-bit accumulator in Java and C++.
Full Solution — all languages
class Solution:
def maxSubArrayLen(self, nums, k):
first = {0: -1}
running = 0
best = 0
for i, v in enumerate(nums):
running += v
if running - k in first:
best = max(best, i - first[running - k])
if running not in first:
first[running] = i
return bestimport java.util.*;
class Solution {
public int maxSubArrayLen(int[] nums, int k) {
Map<Long, Integer> first = new HashMap<>();
first.put(0L, -1);
long running = 0;
int best = 0;
for (int i = 0; i < nums.length; i++) {
running += nums[i];
Integer seen = first.get(running - k);
if (seen != null) best = Math.max(best, i - seen);
first.putIfAbsent(running, i);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxSubArrayLen(vector<int>& nums, int k) {
unordered_map<long long, int> first;
first[0] = -1;
long long running = 0;
int best = 0;
for (int i = 0; i < (int)nums.size(); i++) {
running += nums[i];
auto it = first.find(running - k);
if (it != first.end()) best = max(best, i - it->second);
if (first.find(running) == first.end()) first[running] = i;
}
return best;
}
};/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/ var maxSubArrayLen = function(nums, k) {
const first = new Map([[0, -1]]);
let running = 0, best = 0;
for (let i = 0; i < nums.length; i++) {
running += nums[i];
if (first.has(running - k)) best = Math.max(best, i - first.get(running - k));
if (!first.has(running)) first.set(running, i);
}
return best;
};