Talentd
FleetCode

1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

Medium49.4% acceptance1 company

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 <= 105
  • -104 <= nums[i] <= 104
  • 0 <= target <= 106

Asked at 1 company

Hints open one at a time

Hint 1
Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array.
Hint 2
It can be proved that greedily forming valid subarrays as soon as one is found is optimal.
9:52
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def maxNonOverlapping(self, nums: List[int], target: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,1,1,1,1]
2
Input
[-1,3,5,1,4,2,-9]
6
Your code is saved on this device.Solution