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

本文探讨了一个算法问题,即在给定整数数组中找到两个不重叠子数组,使它们的和等于目标值,同时最小化这两个子数组长度之和。通过滑动窗口和动态规划方法,文章提供了一种解决方案,并通过多个示例进行了解释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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
class Solution {
public:
    int minSumOfLengths(vector<int>& arr, int target) {
        // 由于都是正数,一个起点最多对应一个终点,所有可能的子数组最多有n个
        // 也是由于都是正数才可以用滑动窗口
        int result = INT_MAX;
        const int n = arr.size();
        // min_length[i]表示在i和i之前的合法子数组的最小长度
        vector<int> min_lens(n, INT_MAX);
        int sum = 0;
        int i = 0, j = 0;
        int min_len = INT_MAX;
        while(j < n) {
            sum += arr[j];
            while(i <= j && sum > target) {
                sum -= arr[i];
                i++;
            }
            if (sum == target) {
                int cur_len = j - i + 1;
                min_len = min(min_len, cur_len);
                // 当发现当前合法子数组之前已经有了合法子数组,则更新结果
                if (i > 0 && min_lens[i - 1] != INT_MAX) {
                    result = min(result, cur_len + min_lens[i - 1]);
                }
            }
            // 最后再更新min_lens
            min_lens[j] = min_len;
            j++;
        }
        return result == INT_MAX ? -1 : result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值