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 ([3] and [3]). 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 ([7], [3,4] and [7]), 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

思路: 这题思路有点类似 Subarray Sum Equals K , 那个题是用hashmap存prefixsum , frequency. 这里因为只要找两个subarray,所以存prefixsum和index,如果找到了sum - target代表找到一个区间,那么更新当前的dp[i], dp[i] 代表的是到目前i为止,所能得到的subarray sum和为target的length。如果dp[pre] != -1 && dp[pre] != Integer.MAX_VALUE,代表找到了两个subarray区间,更新res;

这里注意的是,prefixsum index,一定要存0, -1 在hashmap里面,是为了对应 前面X元素就是target的情况,那么length i - pre,刚好= len

class Solution {
    public int minSumOfLengths(int[] arr, int target) {
        if(arr == null || arr.length == 0) {
            return 0;
        }
        //     
        HashMap hashmap = new HashMap();
        hashmap.put(0, -1); // 为了防止,前几个数就是target和,那么算len的时候,
        int n = arr.length;
        int[] dp = new int[n]; // dp里面存,到目前i为止的,和为target的最小的length;
        int sum = 0;
        int res = Integer.MAX_VALUE;
        for(int i = 0; i < n; i++) {
            sum += arr[i];
            dp[i] = i > 0 ? dp[i - 1] : Integer.MAX_VALUE;
            
            if(hashmap.containsKey(sum - target)) {
                int pre = hashmap.get(sum - target);
                // 更新当前的和为target的最小值;
                dp[i] = Math.min(dp[i], i - pre);
                
                // if we find 2 subarry;
                // if pre equals -1 means we only get one sub-array whoes sum eqauls target
                if(pre != -1 && dp[pre] != Integer.MAX_VALUE) {
                    res = Math.min(res, dp[pre] + i - pre);
                }
            }
            hashmap.put(sum, i);
        }
        return res == Integer.MAX_VALUE ? -1: res;
    }
}

 

你可能感兴趣的:(PrefixSum,hashmap)