Maximum Size Subarray Sum Equals k Problem
Description
LeetCode Problem 325.
Given an integer array nums and an integer k, return the maximum length of a subarray that sums to k. If there is not one, return 0 instead.
Example 1:
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.
Example 2:
Input: nums = [-2,-1,2,1], k = 1
Output: 2
Explanation: The subarray [-1, 2] sums to 1 and is the longest.
Constraints:
1 <= nums.length <= 2 * 10^5-10^4 <= nums[i] <= 10^4-10^9 <= k <= 10^9
Solution
Approach: Prefix Sums and a Hash Map of First Positions
Let s[i] be the sum of nums[0..i]. The subarray nums[j+1..i] sums to s[i] - s[j], so it sums to k exactly when s[j] = s[i] - k. For a fixed end i, the longest such subarray starts right after the earliest j with that prefix sum.
So walk through the array once, keeping the running sum s and a hash map first from each prefix sum to the first index where it appeared:
- Start with
first[0] = -1: the empty prefix before index0. Without it, subarrays that start at index0(like[1, -1, 5, -2]in example 1) are missed. - At index
i, addnums[i]tos. Ifs - kis infirst, the subarray fromfirst[s - k] + 1toisums tok; update the answer with its lengthi - first[s - k]. - Store
sonly if it is not already in the map. Overwriting it with a later index would make later subarrays shorter.
Negative numbers are why a sliding window does not work here: the sum does not grow as the window grows, so there is no rule for when to move the left end.
The prefix sums can reach 2 * 109, and s - k can reach 3 * 109, so Java and C++ use 64-bit integers.
Complexity: O(n) time and O(n) extra space for the hash map.
class Solution:
def maxSubArrayLen(self, nums: List[int], k: int) -> int:
first = {0: -1} # prefix sum -> the first index where it appears
s = best = 0
for i, x in enumerate(nums):
s += x # s = nums[0] + ... + nums[i]
if s - k in first: # nums[j + 1 .. i] sums to k, where j = first[s - k]
best = max(best, i - first[s - k])
if s not in first: # keep the earliest index: it gives the longest subarray
first[s] = i
return best