|
| 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 | +fromtypingimportList |
| 40 | + |
| 41 | + |
| 42 | +classSolution: |
| 43 | +defmaxSumTwoNoOverlap(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= [0for_inrange(n+1)] |
| 50 | +fori,ainenumerate(A): |
| 51 | +F[i+1]=F[i]+a |
| 52 | + |
| 53 | +ret=-float("inf") |
| 54 | +forl,min ((L,M), (M,L)): |
| 55 | +foriinrange(n+1-l): |
| 56 | +forjinrange(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 | +returnret |
| 61 | + |
| 62 | + |
| 63 | +if__name__=="__main__": |
| 64 | +assertSolution().maxSumTwoNoOverlap([0,6,5,2,2,5,1,9,4],1,2)==20 |