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个小组的平均数的和要最大的话要怎么分组。
思路:
DP
直接想的话,比如[9,1,2,3,9]分成3组,那就一个一个试,
可以把[9,1,2,3]分2组,最后一个[9]一组,或者[9,1,2]分2组,[3,9]一组,或者[9,1]分2组,[2,3,9]一组
这时候就需要递推了,比如把[9,1,2,3]分2组,最后一个[9]一组,那下一步[9,1,2,3]就需要(1) [9,1,2]一组,3一组,或者(2) [9,1]一组,[2,3]一组,或者(3) [9]一组,[1,2,3]一组,而可以看到,当分成一组的时候,只需要求组内平均数即可。求(1)(2)(3)中较大的平均数,可得[9,1,2,3]分2组的最大平均和。
定义dp[k][i]为0~i的部分分成k组的最大平均和,
那问题又可分解为0~j 分成k-1组,j+1 ~ i分成一组,
即dp[k][i] = dp[k-1][j] + average(j+1 ~ i)
其中average可提前求累加和数组sum, 用(sum[i] - sum[j]) / (i - j)即可
0~i的部分分成k组,那么i至少要为k-1,i = k-1 ~ n-1
0~j的部分分成k-1组,j至少要为k-2, j = k-2 ~ i-1
当k=1时,直接求平均数即可
public double largestSumOfAverages(int[] A, int K) {
if(A == null || A.length == 0) {
return 0;
}
int n = A.length;
double[][] dp = new double[K+1][n];
int[] sum = new int[n];
sum[0] = A[0];
dp[1][0] = A[0];
for(int i = 1; i < n; i++) {
sum[i] = sum[i-1] + A[i];
dp[1][i] = (double)sum[i] / (i+1);
}
//0~j 分成k-1组,j~i分成1组, O(kn^2)
for(int k = 2; k <= K; k++) {
for(int i = k-1; i < n; i++) {
for(int j = k-2; j < i; j++){
//后面平均数要cast到double,不然会截断后再自动cast到double,得不到想要的结果
dp[k][i] = Math.max(dp[k][i], dp[k-1][j] + (double)(sum[i] - sum[j])/(i-j));
}
}
}
return dp[K][n-1];
}