1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
SourceWeekly Contest 201 Q3DifficultyMediumRating1855
Description
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] <= 1040 <= target <= 106
Solutions
Solution 1: Greedy + Prefix Sum + Hash Table
Thinking
Select as many non-overlapping subarrays of sum \(target\) as possible. \(n\le 10^5\) rules out interval DP. When two candidates overlap, keeping the one that ends further left never hurts later choices.
Scan with a prefix-sum set, take the earliest subarray that hits \(target\), then restart after it. The greedy always finishes a piece as soon as possible and leaves more room to the right.
We traverse the array \(nums\), using the method of prefix sum + hash table, to find subarrays with a sum of \(target\). If found, we increment the answer by one, then we set the prefix sum to \(0\) and continue to traverse the array \(nums\) until the entire array is traversed.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the array \(nums\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |