晨哥Leetcode 1031. Maximum Sum of Two Non-Overlapping Subarrays

Given an array A of non-negative integers, return the maximum sum of elements in two non-overlapping (contiguous) subarrays, which have lengths L and M. (For clarification, the L-length subarray could occur before or after the M-length subarray.)
Formally, return the largest V for which V = (A[i] + A[i+1] + … + A[i+L-1]) + (A[j] + A[j+1] + … + A[j+M-1]) and either:
0 <= i < i + L - 1 < j < j + M - 1 < A.length, or
0 <= j < j + M - 1 < i < i + L - 1 < A.length.
Example 1:
Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
Output: 20
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length 2.
Example 2:
Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
Output: 29
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with length 2.
Example 3:
Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
Output: 31
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with length 3.

解析:
这题可以用个笨拙的办法,先从左边算好大小为l, m的subarray最大的值
再从右边过来,算好大小为l,m的subarray最大的值
复杂度也是o(n),不过代码比较丑一些

讨论区大神的算法是这样的, 前面有两个区间 [0…l-1] 和 [l …l+m-1] 从l+m开始往后遍历
每次挪动一格,中间这个区间的sum就update一下,前面那个区间为l的sum也update一下,同时计算前面最大的l subarray
每次算的是中间这个m大小的subarray是一定要包括进去的,前面的区间为l的subarray是选取最大的值
也即:包含中间这个m大小区间,前面最大的和
有点说不清,本质上是我们一直在枚举遍历后面那个大小为M的区间,一个个枚举,(我们枚举的总是在右边的subarray

public int maxSumTwoNoOverlap(int[] a, int l, int m) {
        return Math.max(maxLM(a,l,m), maxLM(a,m,l));
    }
    
    private int maxLM(int[] a, int l, int m) {
        int res = 0, lsum = 0, lmax = 0;
        for(int i= 0; i< l; i++) {
           lsum+=a[i];
        }
        lmax = lsum;
        
        int msum = 0;
        for(int i= l; i< l+m; i++) {
           msum+=a[i];
        }
        res = lmax + msum;
        for(int i= l+m; i< a.length; i++) {
            lsum+=a[i-m] - a[i-l-m];
            lmax = Math.max(lmax, lsum);
            msum+=a[i] - a[i-m];    
            res = Math.max(res, lmax + msum);
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值