[leetcode] 1031. Maximum Sum of Two Non-Overlapping Subarrays

Description

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.

Note:

  1. L >= 1
  2. M >= 1
  3. L + M <= A.length <= 1000
  4. 0 <= A[i] <= 1000

分析

题目的意思是:给你一个数组,求取出L长度的子数组和M长度的子数组,两数组不相交,这道题我不会,找了一个我能看懂的解法,首先是建立一个求和的数组,然后再构造题目中说的两种情况,找出最大值就行了,注意两次遍历的取的遍历区间,特别是n+1,n+1代表的是prefix数组的长度哈,因为最开始加了一个0哈。

代码

class Solution:
    def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
        n=len(A)
        prefix=[0]
        for i in range(n):
            t=prefix[-1]+A[i]
            prefix.append(t)
        maxl=maxm=0
        summ=0
        for i in range(M,n+1-L):
            maxm=max(maxm,prefix[i]-prefix[i-M])
            summ=max(summ,maxm+prefix[i+L]-prefix[i])
            
        for i in range(L,n+1-M):
            maxl=max(maxl,prefix[i]-prefix[i-L])
            summ=max(summ,maxl+prefix[i+M]-prefix[i])
        return summ
            
            

参考文献

[LeetCode] Python, clean O(N), 98%

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值