MediumArrayHash TableGreedyPrefix Sum

Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

LeetCode
1 approach, code in all languages

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^4
  • 0 <= target <= 10^6
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now