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 Sum = Target INPUT nums array: 1 i=0 1 i=1 1 i=2 1 i=3 1 i=4 target = 2 Prefix Sums: 0 1 2 3 4 prefix[i] = sum of nums[0..i] nums = [1,1,1,1,1] target = 2 Find max non-overlapping subarrays ALGORITHM STEPS 1 Init HashMap Store prefix sum with index 0 map = {0: -1}, count = 0 2 Iterate & Compute Calculate prefix sum at each i prefixSum += nums[i] 3 Check for Target If (prefixSum - target) in map Found subarray ending at i count++, reset map 4 Greedy Selection Take earliest ending subarray Maximize non-overlapping Trace: i=1, prefix=2 2-2=0 in map --> subarray [0,1] count=1, reset, continue... i=3: found [2,3], count=2 FINAL RESULT Selected Non-Overlapping Subarrays: Subarray 1: [1, 1] 1 1 sum=2 Subarray 2: [1, 1] 1 1 sum=2 Original Array with Selections: 1 1 1 1 1 Subarray 1 Subarray 2 Output: 2 OK - Maximum found Key Insight: The greedy approach works because taking the earliest-ending subarray with target sum leaves maximum room for future subarrays. Using prefix sums with a hashmap allows O(1) lookup to check if (prefixSum - target) exists, enabling O(n) time complexity overall. TutorialsPoint - Maximum Number of Non-Overlapping Subarrays With Sum Equals Target | Greedy Approach with Prefix Sum
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