当前位置:网站首页>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;
}
}
边栏推荐
- Introduction and use of gateway
- Pycharm terminal enables virtual environment
- Laravel constructor and middleware execution order
- ATM system
- [vulnhub range] thales:1
- [medical segmentation] attention Unet
- [designmode] template method pattern
- Tragedy caused by deleting the console statement
- 【C 语言】 题集 of Ⅹ
- Interface oriented programming
猜你喜欢
随机推荐
ATM系统
爬虫(17) - 面试(2) | 爬虫面试题库
C语言进阶——函数指针
Deep listening array deep listening watch
Interface oriented programming
Binary search tree (basic operation)
Talk about the realization of authority control and transaction record function of SAP system
Tragedy caused by deleting the console statement
最新阿里P7技术体系,妈妈再也不用担心我找工作了
Arduino 控制的双足机器人
运算符
A tour of gRPC:03 - proto序列化/反序列化
Introduction to ThinkPHP URL routing
Geoserver2.18 series (5): connect to SQLSERVER database
As an Android Developer programmer, Android advanced interview
最新Android高级面试题汇总,Android面试题及答案
Tidb cannot start after modifying the configuration file
typescript ts 基础知识之类型声明
01tire+ chain forward star +dfs+ greedy exercise one
The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit








