LeetCode 1477 Find Two Non-overlapping Sub-arrays Each With Target Sum (滑动窗)

You are given an array of integers arr and an integer target.

You have to find two non-overlapping sub-arrays of arr each with a 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.

Constraints:

  • 1 <= arr.length <= 10^5
  • 1 <= arr[i] <= 1000
  • 1 <= target <= 10^6

题目链接:https://leetcode.com/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum/

题目大意:求两段不重复的和为target的子串的最小长度和

题目分析:像这种求两段不重复的问题很容易想到分别从左往右,从右往左计算答案再枚举中点

class Solution {

    private int MAX = 10000000;
    private void prepare(int[] arr, int target, int[] res) {
        int mi = MAX, cur = 0, x = 0, y = 0, n = arr.length;
        while (y < n) {
            while (y < n && cur <= target) {
                cur += arr[y];
                if (cur == target) {
                    mi = Math.min(mi, y - x + 1);
                }
                res[y++] = mi;
            }
            while (x <= y && cur >= target) {
                cur -= arr[x++];
                if (cur == target) {
                    mi = Math.min(mi, y - x);
                    res[y - 1] = mi;
                }
            }
        }
    }

    public int minSumOfLengths(int[] arr, int target) {
        int n = arr.length, ans = MAX;
        int[] l = new int[n];
        int[] r = new int[n];
        prepare(arr, target, l);
        int[] arr2 = new int[n];
        for (int i = 0; i < n; i++) {
            arr2[n - i - 1] = arr[i];
        }
        prepare(arr2, target, r);
        for (int i = 0; i + 1 < n; i++) {
            ans = Math.min(ans, l[i] + r[n - i - 2]);
        }
        return ans >= MAX ? -1 : ans;
    }
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值