Skip to content

Commit a7e31f9

Browse files
authored
Create partition-array-for-maximum-sum.py
1 parent 5b75237 commit a7e31f9

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Time: O(n * k)
2+
# Space: O(k)
3+
4+
class Solution(object):
5+
def maxSumAfterPartitioning(self, A, K):
6+
"""
7+
:type A: List[int]
8+
:type K: int
9+
:rtype: int
10+
"""
11+
W = K+1
12+
dp = [0]*W
13+
for i in xrange(len(A)):
14+
curr_max = 0
15+
# dp[i % W] = 0; # no need in this problem
16+
for k in xrange(1, min(K, i+1) + 1):
17+
curr_max = max(curr_max, A[i-k+1])
18+
dp[i % W] = max(dp[i % W], (dp[(i-k) % W] if i >= k else 0) + curr_max*k)
19+
return dp[(len(A)-1) % W]

0 commit comments

Comments
 (0)