当前位置:网站首页>LeetCode 1477. 找两个和为目标值且不重叠的子数组 每日一题
LeetCode 1477. 找两个和为目标值且不重叠的子数组 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
给你一个整数数组 arr 和一个整数值 target 。
请你在 arr 中找 两个互不重叠的子数组 且它们的和都等于 target 。可能会有多种方案,请你返回满足要求的两个子数组长度和的 最小值 。
请返回满足要求的最小长度和,如果无法找到这样的两个子数组,请返回 -1 。
示例 1:
输入:arr = [3,2,2,4,3], target = 3
输出:2
解释:只有两个子数组和为 3 ([3] 和 [3])。它们的长度和为 2 。
示例 2:输入:arr = [7,3,4,7], target = 7
输出:2
解释:尽管我们有 3 个互不重叠的子数组和为 7 ([7], [3,4] 和 [7]),但我们会选择第一个和第三个子数组,因为它们的长度和 2 是最小值。
示例 3:输入:arr = [4,3,2,6,2,3,4], target = 6
输出:-1
解释:我们只有一个和为 6 的子数组。
示例 4:输入:arr = [5,5,4,4,5], target = 3
输出:-1
解释:我们无法找到和为 3 的子数组。
示例 5:输入:arr = [3,1,1,1,5,1,2,1], target = 3
输出:3
解释:注意子数组 [1,2] 和 [2,1] 不能成为一个方案因为它们重叠了。
提示:
1 <= arr.length <= 10^5
1 <= arr[i] <= 1000
1 <= target <= 10^8来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-two-non-overlapping-sub-arrays-each-with-target-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int minSumOfLengths(int[] arr, int target) {
int n = arr.length;
int[] dp = new int[n];
//要求最小,填充为较大的数
Arrays.fill(dp,Integer.MAX_VALUE / 2);
int ans = Integer.MAX_VALUE;
//双指针
int left = 0;
int sum = 0;
for(int right = 0;right < n;right++){
sum += arr[right];
while(left <= right && sum > target){
sum -= arr[left++];
}
if(sum == target){
dp[right] = right - left + 1;
if(left != 0){
ans = Math.min(ans,dp[left - 1] + dp[right]);
}
}
if(right != 0){
dp[right] = Math.min(dp[right - 1],dp[right]);
}
}
return ans > n ? -1 : ans;
}
}边栏推荐
- Ray and OBB intersection detection
- C语言进阶——函数指针
- [hcsd celebrity live broadcast] teach the interview tips of big companies in person - brief notes
- 23. 合并K个升序链表-c语言
- LocalStorage和SessionStorage
- 【MySql进阶】索引详解(一):索引数据页结构
- Sqlserver2014+: create indexes while creating tables
- Opportunity interview experience summary
- Imitate the choice of enterprise wechat conference room
- typescript ts 基础知识之类型声明
猜你喜欢
随机推荐
【DesignMode】享元模式(Flyweight Pattern)
直接上干货,100%好评
spark调优(三):持久化减少二次查询
Talk about the realization of authority control and transaction record function of SAP system
Detailed explanation of several ideas for implementing timed tasks in PHP
logback. XML configure logs of different levels and set color output
Tragedy caused by deleting the console statement
Binary search tree (features)
【DesignMode】外观模式 (facade patterns)
二叉搜索树(基操篇)
[designmode] flyweight pattern
Sort out several important Android knowledge and advanced Android development interview questions
[medical segmentation] attention Unet
Find tags in prefab in unity editing mode
预测——灰色预测
Introduction and use of gateway
最新Android高级面试题汇总,Android面试题及答案
Opencv personal notes
正在准备面试,分享面经
Master this promotion path and share interview materials


![[C language] question set of X](/img/17/bfa57de183c44cf0a3c6637bb65a9d.jpg)





