思路如下代码,可以进一步内存优化,取消dp数组,直接用sum即可。
/*
* @lc app=leetcode id=1031 lang=cpp
*
* [1031] Maximum Sum of Two Non-Overlapping Subarrays
*/
// @lc code=start
class Solution {
public:
int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {
int N = nums.size();
int sumAL=0, sumAR=0, sumBL=0, sumBR = 0;
vector<int> dpAL(N+2, 0), dpAR(N+2, 0);
vector<int> dpBL(N+2, 0), dpBR(N+2, 0);
for(int i=0;i<firstLen-1;i++){
sumAL += nums[i];
}
for(int i=0;i<secondLen-1;i++){
sumBL += nums[i];
}
for(int i=firstLen;i<=N;i++){
sumAL += nums[i-1];
dpAL[i] = max(dpAL[i-1], sumAL);
sumAL -= nums[i-firstLen];
}
for(int i=secondLen;i<=N;i++){
sumBL += nums[i-1];
dpBL[i] = max(dpBL[i-1], sumBL);
sumBL -= nums[i-secondLen];
}
for(int i=N-1;i>N-firstLen;i--){
sumAR += nums[i];
}
for(int i=N-1;i>N-secondLen;i--){
sumBR += nums[i];
}
for(int i=N-firstLen;i>0;i--){
sumAR += nums[i];
dpAR[i] = max(dpAR[i+1], sumAR);
sumAR -= nums[i+firstLen-1];
}
for(int i=N-secondLen;i>0;i--){
sumBR += nums[i];
dpBR[i] = max(dpBR[i+1], sumBR);
sumBR -= nums[i+secondLen-1];
}
int ans = 0;
for(int i=1;i<=N;i++){
ans = max(ans, dpAL[i] + dpBR[i]);
ans = max(ans, dpBL[i] + dpAR[i]);
}
return ans;
}
};
// @lc code=end