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
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
i, n = 0, len(nums)
ans = 0
while i < n:
s = 0
seen = {0}
while i < n:
s += nums[i]
if s - target in seen:
ans += 1
break
i += 1
seen.add(s)
i += 1
return ans
class Solution {
public int maxNonOverlapping(int[] nums, int target) {
int i = 0, n = nums.length;
int ans = 0;
while (i < n) {
int s = 0;
Set<Integer> seen = new HashSet<>();
seen.add(0);
while (i < n) {
s += nums[i];
if (seen.contains(s - target)) {
++ans;
break;
}
++i;
seen.add(s);
}
++i;
}
return ans;
}
}
class Solution {
public:
int maxNonOverlapping(vector<int>& nums, int target) {
int i = 0, n = nums.size();
int ans = 0;
while (i < n) {
int s = 0;
unordered_set<int> seen;
seen.insert(0);
while (i < n) {
s += nums[i];
if (seen.count(s - target)) {
++ans;
break;
}
++i;
seen.insert(s);
}
++i;
}
return ans;
}
};
func maxNonOverlapping(nums []int, target int) int {
i, n, ans := 0, len(nums), 0
for i < n {
s := 0
seen := map[int]bool{0: true}
for i < n {
s += nums[i]
if seen[s-target] {
ans++
break
}
seen[s] = true
i++
}
i++
}
return ans
}