- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path1043.py
43 lines (31 loc) · 1.09 KB
/
1043.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
'''
Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning.
Example 1:
Input: A = [1,15,7,9,2,5,10], K = 3
Output: 84
Explanation: A becomes [15,15,15,9,10,10,10]
Note:
1 <= K <= A.length <= 500
0 <= A[i] <= 10^6
'''
classSolution(object):
defmaxSumAfterPartitioning(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
ifnotA:
return0
N=len(A)
dp= [0]*(N+1)
forindex_iinrange(N):
maxi=0
forindex_jinrange(index_i, index_i-K, -1):
ifindex_j>=0andindex_j<len(A):
maxi=max(maxi, A[index_j])
dp[index_i+1] =max(dp[index_i+1], maxi*(index_i-index_j+1)+dp[index_j])
# print index_i, maxi
# print dp
returndp[-1]