Maximum Number of Non-Overlapping Subarrays With Sum Equals Target Problem
Description
LeetCode Problem 1546.
Given an array nums and an integer target, return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.
Example 1:
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).
Example 2:
Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.
Constraints:
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^40 <= target <= 10^6
Solution
Approach: Greedy with Prefix Sums
Among all subarrays with sum target, the classic interval-scheduling argument applies: picking the one that ends first is always safe. Any optimal answer can swap its first subarray for that one without overlapping anything else, since it ends no later.
So scan from left to right and stop at the first position where some subarray ending there has sum target. Use prefix sums: a subarray ending at the current position has sum target exactly when prefix - target is one of the earlier prefix sums. Keep those in a hash set seen, starting with 0 for the empty prefix.
- When
prefix - targetis inseen, count one subarray and clearseen: the next subarray must start after this one, so older prefix sums are no longer allowed as starting points. Then add the currentprefixas the new starting point. - Otherwise just add
prefixtoseen.
The values can be negative, so a sliding window does not work here. Note also that target can be 0: with nums = [0, 0, 0] each single 0 counts, giving 3.
Complexity: O(n) time and O(n) extra space for the set.
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
count = 0
prefix = 0
seen = {0} # prefix sums since the end of the last chosen subarray
for x in nums:
prefix += x
if prefix - target in seen:
# The earliest-ending subarray with sum target: take it and start over after it.
count += 1
seen = set()
seen.add(prefix)
return count