1031. Maximum Sum of Two Non-Overlapping Subarrays(sliding window + DP)

This is an implicit sliding window problem. It is almost the same as buying and selling the stock 3.

The idea is that we gonna set up a middle line, and the line would keep moving forward. When is it moving, we would see if there is any better option for the answer.

The left side of the middle line is the first subarray, and the right side of the middle line is the second subarray. When the line is moving, a new element would be added to the left-hand side, we would check if it would increase the sum of the first subarray or not, if it cannot, we just skip. For the right-hand side, there also is a new element coming in, we need to check if it would increase the sum of the second subarray or not.

We need to query the sum of a subarray often to precalculate the prefix sum and make this query O(1).

class Solution {
public:
    int maxSumTwoNoOverlap(vector<int>& nums, int firstLen, int secondLen) {
        int n = nums.size();
        vector<int> prefixSum(n + 1, 0);
        prefixSum[1] = nums[0];
        for(int i = 2; i <= n; i++)prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
        int sumL = 0;
        int res = 0;
        for(int i = firstLen; i + secondLen - 1 < n; i++){
            sumL = max(sumL, prefixSum[i] - prefixSum[i - firstLen]);
            res = max(res, sumL + prefixSum[i + secondLen] - prefixSum[i]);
        }
        int sumM = 0;
        for(int i = secondLen; i + firstLen - 1 < n; i++){
            sumM = max(sumM, prefixSum[i] - prefixSum[i - secondLen]);
            res = max(res, sumM + prefixSum[i + firstLen] - prefixSum[i]);
        }
        return res;
        
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值