Skip to content

Commit 877a601

Browse files
1031 Maximum Sum of Two Non-Overlapping Subarrays.py
1 parent 000c69a commit 877a601

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#!/usr/bin/python3
2+
"""
3+
Given an array A of non-negative integers, return the maximum sum of elements in
4+
two non-overlapping (contiguous) subarrays, which have lengths L and M. (For
5+
clarification, the L-length subarray could occur before or after the M-length
6+
subarray.)
7+
8+
Formally, return the largest V for which V = (A[i] + A[i+1] + ... + A[i+L-1]) +
9+
(A[j] + A[j+1] + ... + A[j+M-1]) and either:
10+
11+
0 <= i < i + L - 1 < j < j + M - 1 < A.length, or
12+
0 <= j < j + M - 1 < i < i + L - 1 < A.length.
13+
14+
15+
Example 1:
16+
Input: A = [0,6,5,2,2,5,1,9,4], L = 1, M = 2
17+
Output: 20
18+
Explanation: One choice of subarrays is [9] with length 1, and [6,5] with length
19+
2.
20+
21+
Example 2:
22+
Input: A = [3,8,1,3,2,1,8,9,0], L = 3, M = 2
23+
Output: 29
24+
Explanation: One choice of subarrays is [3,8,1] with length 3, and [8,9] with
25+
length 2.
26+
27+
Example 3:
28+
Input: A = [2,1,5,6,0,9,5,0,3,8], L = 4, M = 3
29+
Output: 31
30+
Explanation: One choice of subarrays is [5,6,0,9] with length 4, and [3,8] with
31+
length 3.
32+
33+
Note:
34+
L >= 1
35+
M >= 1
36+
L + M <= A.length <= 1000
37+
0 <= A[i] <= 1000
38+
"""
39+
from typing import List
40+
41+
42+
class Solution:
43+
def maxSumTwoNoOverlap(self, A: List[int], L: int, M: int) -> int:
44+
"""
45+
Prefix sum + Brute force O(N^2)
46+
two pointer i, j
47+
"""
48+
n = len(A)
49+
F = [0 for _ in range(n + 1)]
50+
for i, a in enumerate(A):
51+
F[i+1] = F[i] + a
52+
53+
ret = -float("inf")
54+
for l, m in ((L, M), (M, L)):
55+
for i in range(n + 1 - l):
56+
for j in range(i + l, n + 1 - m): # upper needs +1 here
57+
cur = F[i + l] - F[i] + F[j + m] - F[j]
58+
ret = max(ret, cur)
59+
60+
return ret
61+
62+
63+
if __name__ == "__main__":
64+
assert Solution().maxSumTwoNoOverlap([0,6,5,2,2,5,1,9,4], 1, 2) == 20

0 commit comments

Comments
 (0)