LeetCode 1031. Maximum Sum of Two Non-Overlapping Subarrays 解题报告(python)

1031. Maximum Sum of Two Non-Overlapping Subarrays

  1. Maximum Sum of Two Non-Overlapping Subarrays python solution

题目描述

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.

在这里插入图片描述

解析

题目要求在在数组中找到连续的L,M不重叠子串数字和的最大值。
因为要求不重叠,所以存在两种情况:
第一种:L子串在M子串的左边
第二种:L子串在M子串的右边
对于第一种情况,我们先求L子串的最大值,注意右边要留M宽度给M子串,先确定L的最大值,然后再求L+M的最大值。
第二种情况正好相反,先求M最大值,再求L+M的最大值。

class Solution:
    def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
        for i in range(1,len(A)):
            A[i]+=A[i-1]
            
        res, Lmax, Mmax=A[L+M-1], A[L-1], A[M-1]
        for i in range(L+M,len(A)):
        # window  | --- L --- | --- M --- |
            Lmax=max(Lmax, A[i-M]-A[i-L-M])  
        # window  | --- M --- | --- L --- |
            Mmax=max(Mmax, A[i-L]-A[i-L-M])
            res= max(res,Lmax+A[i]-A[i-M], Mmax+A[i]-A[i-L])
            
        return res
        

Reference

https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/discuss/278251/JavaC%2B%2BPython-O(N)Time-O(1)-Space

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值