1031. Maximum Sum of Two Non-Overlapping Subarrays
- 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