Given an array nums and an integer target, return the maximum number ofnon-emptynon-overlapping subarrays such that the sum of values in each subarray is equal totarget.
Input: nums =[-1,3,5,1,4,2,-9], target =6Output: 2Explanation: 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.
To maximize the number of non-overlapping subarrays with sum equal to target, we can use a greedy approach: whenever we find a subarray ending at the current index with the required sum, we start a new search from the next index. We use a prefix sum and a hash set to efficiently check for such subarrays.
classSolution {
public:int maxNonOverlapping(vector<int>& nums, int target) {
unordered_set<int> seen{0};
int ans =0, sum =0;
for (int x : nums) {
sum += x;
if (seen.count(sum - target)) {
ans++;
seen.clear();
seen.insert(0);
sum =0;
} else {
seen.insert(sum);
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funcmaxNonOverlapping(nums []int, targetint) int {
seen:=map[int]bool{0: true}
ans, sum:=0, 0for_, x:=rangenums {
sum+=xifseen[sum-target] {
ans++seen = map[int]bool{0: true}
sum = 0 } else {
seen[sum] = true }
}
returnans}
import java.util.*;
classSolution {
publicintmaxNonOverlapping(int[] nums, int target) {
Set<Integer> seen =new HashSet<>();
seen.add(0);
int ans = 0, sum = 0;
for (int x : nums) {
sum += x;
if (seen.contains(sum - target)) {
ans++;
seen.clear();
seen.add(0);
sum = 0;
} else {
seen.add(sum);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funmaxNonOverlapping(nums: IntArray, target: Int): Int {
val seen = mutableSetOf(0)
var ans = 0var sum = 0for (x in nums) {
sum += x
if ((sum - target) in seen) {
ans++ seen.clear()
seen.add(0)
sum = 0 } else {
seen.add(sum)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defmaxNonOverlapping(self, nums: list[int], target: int) -> int:
seen = {0}
ans =0 s =0for x in nums:
s += x
if s - target in seen:
ans +=1 seen = {0}
s =0else:
seen.add(s)
return ans
use std::collections::HashSet;
impl Solution {
pubfnmax_non_overlapping(nums: Vec<i32>, target: i32) -> i32 {
letmut seen = HashSet::new();
seen.insert(0);
letmut ans =0;
letmut sum =0;
for x in nums {
sum += x;
if seen.contains(&(sum - target)) {
ans +=1;
seen.clear();
seen.insert(0);
sum =0;
} else {
seen.insert(sum);
}
}
ans
}
}