[
dp
accumulate
sliding window
]
Leetcode 1031. Maximum Sum of Two Non-Overlapping Subarrays
Problem statement
https://leetcode.com/problems/maximum-sum-of-two-non-overlapping-subarrays/
Solution
There is O(n^2)
solution, which pass given constraints. However we can do better.
- First of all, there is two cases, when interval of length
L
is beforM
and the opposite. - Let us fix interval of length
L
. Then what choice we have forM
if it is to the right ofL
?
Complexity
It is O(n)
for time and space.
Code
class Solution:
def maxSumTwoNoOverlap(self, A, L, M):
def maxSum(L, M):
lft = [acc[i] - acc[i-L] for i in range(L, n + 1 - M)]
lft = list(accumulate(lft, max))
rgh = [acc[i+M] - acc[i] for i in range(L, n + 1 - M)]
rgh = list(accumulate(rgh[::-1], max))[::-1]
return max(x + y for x, y in zip(lft, rgh))
acc = [0] + list(accumulate(A))
n = len(A)
return max(maxSum(L, M), maxSum(M, L))