Comment on page

# 1477.Find-Two-Non-overlapping-Sub-arrays-Each-With-Target-Sum

## 题目描述

Given an array of integers arr and an integer target.
You have to find two non-overlapping sub-arrays of arr each with sum equal target. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is minimum.
Return the minimum sum of the lengths of the two required sub-arrays, or return -1 if you cannot find such two sub-arrays.
Example 1:
Input: arr = [3,2,2,4,3], target = 3
Output: 2
Explanation: Only two sub-arrays have sum = 3 ( and ). The sum of their lengths is 2.
Example 2:
Input: arr = [7,3,4,7], target = 7
Output: 2
Explanation: Although we have three non-overlapping sub-arrays of sum = 7 (, [3,4] and ), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
Example 3:
Input: arr = [4,3,2,6,2,3,4], target = 6
Output: -1
Explanation: We have only one sub-array of sum = 6.
Example 4:
Input: arr = [5,5,4,4,5], target = 3
Output: -1
Explanation: We cannot find a sub-array of sum = 3.
Example 5:
Input: arr = [3,1,1,1,5,1,2,1], target = 3
Output: 3
Explanation: Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.
Constraints:
1 <= arr.length <= 10^5
1 <= arr[i] <= 1000
1 <= target <= 10^8

## 代码

### Approach #1 PreSum + HashMap

Time: O(N) && Space: O(N)
class Solution {
public int minSumOfLengths(int[] arr, int target) {
HashMap<Integer, Integer> map = new HashMap();
int sum = 0;
map.put(0, -1);
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
map.put(sum, i);
}
sum = 0;
Integer result = Integer.MAX_VALUE;
Integer lsize = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
// left subarray
if (map.containsKey(sum - target)) {
int len = i - map.get(sum - target);
lsize = Math.min(len, lsize);
}
// right subarray
if (map.containsKey(sum + target) && lsize < Integer.MAX_VALUE) {
int len = map.get(sum + target) - i;
result = Math.min(result, len + lsize);
}
}
return result == Integer.MAX_VALUE ? -1 : result;
}
}

### Approach #2 PreSum Sliding Window

public int minSumOfLengths(int[] arr, int target) {
int n = arr.length;
int best[] = new int[n];
Arrays.fill(best, Integer.MAX_VALUE);
int sum = 0, start = 0, ans = Integer.MAX_VALUE, bestSoFar = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
sum += arr[i];
while (sum > target){
sum -= arr[start];
start++;
}
if (sum == target){
if (start > 0 && best[start - 1] != Integer.MAX_VALUE) {
ans = min(ans, best[start - 1] + i - start + 1);
}
bestSoFar = min(bestSoFar, i - start + 1);
}
best[i] = bestSoFar;
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}