Maximum Number of Non-Overlapping Subarrays With Sum Equals Target
Given an array nums and an integer target.
Return the maximum number of non-emptynon-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.
class Solution {
public int maxNonOverlapping(int[] nums, int target) {
// Map of prefix sum -> Latest index for this prefix sum
HashMap<Integer, Integer> map = new HashMap<>();
// arr[i] -> Maximum Number of Non-Overlapping Subarrays With Sum Equals Target upto i
int[] arr = new int[nums.length];
map.put(0, -1);
int prefix = 0;
for (int i = 0; i < arr.length; i++) {
prefix += nums[i];
int ans = 0;
if (map.containsKey(prefix - target)) {
if (map.get(prefix - target) != -1)
ans = arr[map.get(prefix - target)];
ans += 1;
}
map.put(prefix, i);
arr[i] = Math.max(ans, i > 0 ? arr[i - 1] : Integer.MIN_VALUE);
}
return arr[arr.length - 1];
}
}