813. Largest Sum of Averages
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.
Note:
1 <= A.length <= 100
.1 <= A[i] <= 10000
.1 <= K <= A.length
.- Answers within
10^-6
of the correct answer will be accepted as correct.
题意分析: 给出一个列表,和一个整数K,将列表分为K部分,求这K个列表的平均值之和的最大值
题目思路: 动态规划, 假设dp[k][j]为将列表[0 : j](闭区间)分为K部分所能得到的平均值之和的最大值,那么dp[k][i] = max(dp[k-1][j]), 其中j属于[k-1, i)
AC代码:
class Solution:
def largestSumOfAverages(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: float
"""
length = len(A)
dp = [[0.0 for i in range(length)] for i in range(K)]
sum_array = [0] * (length+1)
for i in range(1, length+1):
sum_array[i] = sum_array[i-1] + A[i-1]
for i in range(length):
dp[0][i] = sum_array[i+1]/(i+1)
for k in range(1, K):
for i in range(k, length):
for j in range(k-1, i):
dp[k][i] = max(dp[k][i], dp[k-1][j] + \
(sum_array[i+1] - sum_array[j+1])/(i-j))
return dp[K-1][length-1]