当前位置:网站首页>LeetCode 1031. 两个非重叠子数组的最大和 每日一题
LeetCode 1031. 两个非重叠子数组的最大和 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
给出非负整数数组 A ,返回两个非重叠(连续)子数组中元素的最大和,子数组的长度分别为 L 和 M。(这里需要澄清的是,长为 L 的子数组可以出现在长为 M 的子数组之前或之后。)
从形式上看,返回最大的 V,而 V = (A[i] + A[i+1] + ... + A[i+L-1]) + (A[j] + A[j+1] + ... + A[j+M-1]) 并满足下列条件之一:
0 <= i < i + L - 1 < j < j + M - 1 < A.length, 或
0 <= j < j + M - 1 < i < i + L - 1 < A.length.
示例 1:
输入:A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
输出:20
解释:子数组的一种选择中,[9] 长度为 1,[6,5] 长度为 2。
示例 2:输入:A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
输出:29
解释:子数组的一种选择中,[3,8,1] 长度为 3,[8,9] 长度为 2。
示例 3:输入:A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
输出:31
解释:子数组的一种选择中,[5,6,0,9] 长度为 4,[0,3,8] 长度为 3。
提示:
L >= 1
M >= 1
L + M <= A.length <= 1000
0 <= A[i] <= 1000来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-sum-of-two-non-overlapping-subarrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
java
class Solution {
public int maxSumTwoNoOverlap(int[] nums, int firstLen, int secondLen) {
int n = nums.length;
//前缀和
int[] sum = new int[n + 1];
for(int i = 0;i < n;i++){
sum[i + 1] = sum[i] + nums[i];
}
//交换
if(firstLen > secondLen){
firstLen ^= secondLen;
secondLen ^= firstLen;
firstLen ^= secondLen;
}
int[][] dp = new int[n + 1][2];
int ans = 0;
//从第firstLen开始
for(int i = firstLen;i <= n;i++){
//已当前元素为结束的前firstLen的和
int s1 = sum[i] - sum[i - firstLen];
dp[i][0] = Math.max(dp[i - 1][0],s1);
ans = Math.max(ans,s1 + dp[i - firstLen][1]);
if(i >= secondLen){
int s2 = sum[i] - sum[i - secondLen];
dp[i][1] = Math.max(dp[i - 1][1],s2);
ans = Math.max(ans,s2 + dp[i - secondLen][0]);
}
}
return ans;
}
}
边栏推荐
- dapp丨defi丨nft丨lp单双币流动性挖矿系统开发详细说明及源码
- Temperature sensor chip used in temperature detector
- Spark Tuning (III): persistence reduces secondary queries
- ATM system
- 【PHP】PHP接口继承及接口多继承原理与实现方法
- OpenGL personal notes
- 水平垂直居中 方法 和兼容
- Deep listening array deep listening watch
- Opportunity interview experience summary
- JS modularization
猜你喜欢
谈谈 SAP 系统的权限管控和事务记录功能的实现
HAVE FUN | “飞船计划”活动最新进展
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑
The difference and working principle between compiler and interpreter
爬虫(17) - 面试(2) | 爬虫面试题库
"The" "PIP" "entry cannot be recognized as the name of a cmdlet, function, script file, or runnable program."
Introduction and use of gateway
Personal notes of graphics (1)
删除 console 语句引发的惨案
整理几个重要的Android知识,高级Android开发面试题
随机推荐
面向接口编程
二叉搜索树(特性篇)
值得一看,面试考点与面试技巧
字节跳动高工面试,轻松入门flutter
模拟Servlet的本质
Interface oriented programming
Usage of config in laravel
谎牛计数(春季每日一题 53)
二叉搜索树(基操篇)
最新Android面试合集,android视频提取音频
【Android -- 数据存储】使用 SQLite 存储数据
[hcsd celebrity live broadcast] teach the interview tips of big companies in person - brief notes
字节跳动Android面试,知识点总结+面试题解析
Ray and OBB intersection detection
Pisa-Proxy SQL 解析之 Lex & Yacc
Laravel service provider instance tutorial - create a service provider test instance
如何选择合适的自动化测试工具?
The differences between exit, exit (0), exit (1), exit ('0 '), exit ('1'), die and return in PHP
JS中null NaN undefined这三个值有什么区别
ATM system