Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
1 approach, code in every language
Problem description
You are given an integer array and an integer target. A candidate is any contiguous subarray whose elements add up to exactly the target value.
Select as many of these candidate subarrays as possible such that no two chosen subarrays share an index. Return the maximum count of non-overlapping subarrays you can pick.
Example 1
Input: nums = [1,1,1,1,1], target = 2
Output: 2
Two disjoint pairs such as indices [0,1] and [2,3] each sum to 2. A third disjoint pair cannot fit in the single leftover element.
Example 2
Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
The subarrays [5,1] and [4,2] both sum to 6 and do not overlap, giving a maximum count of 2.
Constraints
1 <= nums.length <= 10^5-10^4 <= nums[i] <= 10^40 <= target <= 10^6
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free