1031. 两个非重叠子数组的最大和
力扣1031题:
给你一个整数数组 nums 和两个整数 firstLen 和 secondLen,请你找出并返回两个非重叠 子数组 中元素的最大和,长度分别为 firstLen 和 secondLen 。
长度为 firstLen 的子数组可以出现在长为 secondLen 的子数组之前或之后,但二者必须是不重叠的。
子数组是数组的一个 连续 部分。
示例 1:
输入:nums = [0,6,5,2,2,5,1,9,4], firstLen = 1, secondLen = 2
输出:20
解释:子数组的一种选择中,[9] 长度为 1,[6,5] 长度为 2。
示例 2:
输入:nums = [3,8,1,3,2,1,8,9,0], firstLen = 3, secondLen = 2
输出:29
解释:子数组的一种选择中,[3,8,1] 长度为 3,[8,9] 长度为 2。
示例 3:
输入:nums = [2,1,5,6,0,9,5,0,3,8], firstLen = 4, secondLen = 3
输出:31
解释:子数组的一种选择中,[5,6,0,9] 长度为 4,[0,3,8] 长度为 3。
思路1:
采用 前缀和 + 动态规划的思路:
1、用pre数组保存原数组的前缀和,其中pre[0] = 0;
2、用dp[i][0]表示前i个元素中连续的较短子串的最大和,用dp[i][1]表示前i个元素中连续的较长子串的最大和
3、用sum保存结果,sum = max(max(sum,pre[i]-pre[i-firstLen]+dp[i-firstLen][1]) , pre[i]-pre[i-secondLen]+dp[i-secondLen][0]); 其中 pre[i]-pre[i-firstLen]+dp[i-firstLen][1]的含义为,取i-firstLen的子数组,及其前i-firstLeng 个元素的最大连续secondLen个元素的和。
class Solution {
public:
int maxSumTwoNoOverlap(vector<int>& a, int firstLen, int secondLen) {
int len = a.size();
vector<int>pre(len+1);
vector<vector<int>>dp(len+1,vector<int>(2));
if(firstLen > secondLen){
swap(firstLen,secondLen);
}
pre[0] = 0;
//前缀和
for(int i = 0 ; i < len ;i++){
pre[i+1] = pre[i]+a[i];
}
int max1 = 0,max2 = 0,sum = 0;
for(int i = firstLen;i <= len ;i++){
if(pre[i] - pre[i-firstLen] > max1){
max1 = pre[i] - pre[i-firstLen];
}
if(i >= secondLen){
if(max2 < pre[i] - pre[i-secondLen]){
max2 = pre[i] - pre[i-secondLen];
}
if(i >= firstLen+secondLen){
// sum = max(sum,当前 i-firstLen 到 i 的元素和 + 前i-firstLen的最大元素和,当前 i-secondLen 到 i 的元素和 + 前i-secondLen的最大元素和)
sum = max(max(sum,pre[i]-pre[i-firstLen]+dp[i-firstLen][1]),pre[i]-pre[i-secondLen]+dp[i-secondLen][0]);
}
}
// dp[i][0] 存储的是前i个元素 最大 较短的连续子数组和
// dp[i][1] 存储的是前i个元素 最大 较长的连续子数组和
dp[i][0] = max1;
dp[i][1] = max2;
}
return sum;
}
};