又是一道dp的题目,还是给出一个超时的解。

 1 class Solution:
 2     def maxSumAfterPartitioning(self, A: 'List[int]', K: int) -> int:
 3         n = len(A)
 4         dp = [0] * (n+1)
 5         for i in range(n+1):
 6             curmax = 0
 7             for j in range(1,K+1):
 8                 if i-j>=0:
 9                     last = dp[i-j]
10                     cur = max(A[i-j:i])*j
11                     curmax = max(curmax,last+cur)
12                 else:
13                     break
14             dp[i] = curmax
15         return dp[n]

经过分析,猜测上面的代码超时的主要问题是在第10行,每次重新计算切片的最大值。

因此尝试改进,代码如下:

 1 class Solution:
 2     def maxSumAfterPartitioning(self, A: 'List[int]', K: int) -> int:
 3         n = len(A)
 4         dp = [0] * (n+1)
 5         for i in range(n+1):
 6             curmax = 0
 7             premax = 0
 8             for j in range(1,K+1):
 9                 if i-j >= 0:
10                     last = dp[i-j]
11                     premax = max(premax,A[i-j])
12                     cur = premax*j
13                     curmax = max(curmax,last+cur)
14                 else:
15                     break
16             dp[i] = curmax
17         return dp[n]

使用premax变量来存储切片的最大值,而省去了每次调用max()函数来进行计算,从而提高效率。最终获得了AC的结果。

posted on 2019-05-26 08:10  Sempron2800+  阅读(172)  评论(0编辑  收藏  举报