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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-sum-of-averages
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
动态规划,dp[i][k]标识从A[i,A.lenght]分成k组的平均值的最大。那么我们就可以把下一个状态,dp[i][k+1] 看成从[i, lenght]中分成两段,前一段的平均值 + 后一段的平均值。
dp[i][k] = max(dp[i][k], (avg(i, j) + dp[j][k-1]))
class Solution {
public double largestSumOfAverages(int[] A, int K) {
double [][]dp = new double[A.length][K];
double []sum = new double[A.length + 1];
sum[0] = A[0];
for (int i = 1; i < A.length; i++) {
sum[i] = sum[i - 1] + A[i];
}
dp[0][0] = sum[A.length - 1] / A.length;
for (int i = 1; i < A.length; i++) {
dp[i][0] = (sum[A.length - 1] - sum[i - 1]) / (A.length - i);
}
for (int k = 1; k < K; k++) {
for (int i = 0; i < A.length; i++) {
for (int j = i + 1; j < A.length; j++) {
dp[i][k] = Math.max(dp[i][k], (sum[j - 1] - sum[i] + A[i]) / (double)(j - i) + dp[j][k - 1]);
}
}
}
return dp[0][K - 1];
}
}