"""
We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?
Note that our partition must use every number in A, and that scores are not necessarily integers.
Example:
Input:
A = [9,1,2,3,9]
K = 3
Output: 20
Explanation:
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
"""
"""
这题目的思想是基于一个事实:一个数组分割之后肯定是份数越多得到的平均值就越大。
我们假设dp[i][k]表示为数组A【0~i】分割k份得到的最大平均值。
因为最后一个分割点可以出现在任何部分(实际上也得出现在大于k-1个位置之后),所以
dp[i][k]=max(dp[i][k], dp[j][k-1]+sum(j~i)/(i-j)) 其中j在j之前的地方j<i,
因此可以把这个递推式理解为重新选择最后一个分割点的最大处。
当然,要迅速完成sum段求和还需要一个小函数。
传送门:https://blog.csdn.net/weixin_37373020/article/details/81543069
"""
class Solution:
def largestSumOfAverages(self, A, K):
sums = [0]
for a in A:
sums.append(sums[-1]+a) #sums[i] = A[0]+A[1]+...A[i-1]
def gap_sum(i, j):
return sums[j]-sums[i]
dp = [[0 for x in range(K+1)] for y in range(len(A)+1)]
for i in range(1, len(A)+1):
dp[i][1] = gap_sum(0, i)/i
for k in range(2, K+1):
for i in range(k, len(A)+1):
for j in range(i):
dp[i][k] = max(dp[i][k], dp[j][k-1]+gap_sum(j, i)/(i-j))
return dp[len(A)][K]