Maximum Number of Non-Overlapping Subarrays With Sum Equals Target - Problem

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.

A subarray is a contiguous part of an array. Two subarrays are non-overlapping if they do not share any common elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,1,1,1,1], target = 2
Output: 2
💡 Note: We can form 2 non-overlapping subarrays: [1,1] (sum=2) and [1,1] (sum=2). The last element [1] cannot form another subarray with sum=2.
Example 2 — Single Elements
$ Input: nums = [-1,1,5,1,1], target = 1
Output: 3
💡 Note: We can form 3 non-overlapping subarrays: [1], [1], and [1]. Each single element equals the target.
Example 3 — Mixed Values
$ Input: nums = [-1,-1,1,1,1], target = 0
Output: 1
💡 Note: We can form 1 subarray: [-1,1] (sum=0). The remaining elements [-1,1,1] could form [-1,1] but we already used one -1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104
  • 0 ≤ target ≤ 106

Visualization

Tap to expand
Maximum Non-Overlapping Subarrays with Target SumInput:11111target = 2Process:Subarray 1: sum=2Subarray 2: sum=2leftoverOutput:Maximum count: 2Greedy approach: take each valid subarray as soon as found
Understanding the Visualization
1
Input
Array [1,1,1,1,1] with target sum 2
2
Process
Greedily find subarrays that sum to target
3
Output
Maximum count of non-overlapping subarrays
Key Takeaway
🎯 Key Insight: Use greedy strategy with prefix sums - take each valid subarray immediately to maximize the total count
Asked in
Google 12 Amazon 8 Microsoft 6
25.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen