Description:
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.
问题描述:
我们把数组A分为K个相邻的组,最终分数等于每个组的平均数之和。我们能达到的最大的分数是多少?
需要注意,我们必须用上A的每个数,并且分数不必是整数
问题分析:
回溯法
有两个变量,下标index和K.
我们需要对回溯过程优化,因此维护一个二维数组保存状态
为了进一步优化,预先计算了前缀数组
既然是分组,我的想法就是一段一段的求和
例如[1, 2, 3, 4, 5],它的前缀数组为[1, 3, 6, 10, 15]
若将其分为[1, 2]和[3, 4, 5]两份
那么通过前缀数组计算十分方便:
result=(3−1+1)/2+(15−6+3)/3=5.5
r
e
s
u
l
t
=
(
3
−
1
+
1
)
/
2
+
(
15
−
6
+
3
)
/
3
=
5.5
解法(dfs + memorization):
class Solution {
public double largestSumOfAverages(int[] A, int K) {
int len = A.length;
double[] sum = new double[len];
sum[0] = A[0];
//sum为前缀数组,可以提高计算效率
for(int i = 1;i < len;i++){
sum[i] += sum[i - 1] + A[i];
}
//维护一个二维数组,保存状态
double[][] dp = new double[len][K + 1];
return backTrack(A, sum, 0, K, dp);
}
public double backTrack(int[] A, double[] sum, int index, int K, double[][] dp){
if(K == 1){
return (sum[A.length - 1] - sum[index] + A[index]) / (A.length - index);
}
if(dp[index][K] != 0) return dp[index][K];
for(int i = index;i <= A.length - K;i++){
//每往下递归,即开始新的分组,分组的和通过前缀数组来求
dp[index][K] = Math.max(dp[index][K], (((sum[i] - sum[index] + A[index]) * 1.0) / (i - index + 1)) + backTrack(A, sum, i + 1, K - 1, dp));
}
return dp[index][K];
}
}