[leetcode]Largest Sum of Averages
链接:https://leetcode.com/problems/largest-sum-of-averages/description/
Question
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 1
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.
Solution
class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
int size = A.size();
std::vector<double> sum(size, 0);
std::vector<std::vector<double> > avg;
avg.resize(size);
for (int i = 0; i < size; i++) avg[i].resize(size);
// dp[k][i]表示A[i:]最多k次分割的最大值(the sum of the average of each group)
std::vector<std::vector<double> > dp;
dp.resize(K+1, vector<double>());
for (int i = 0; i <= K; i++) dp[i].resize(size);
sum[0] = A[0];
for (int i = 1; i < size; i++) sum[i] = sum[i-1]+A[i];
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (i == 0) avg[i][j] = sum[j]/(j+1);
else avg[i][j] = (sum[j]-sum[i-1])/(j-i+1);
}
}
// 第一次相当于不分割
for (int i = 0; i < size; i++) dp[1][i] = avg[i][size-1];
for (int k = 2; k <= K; k++) {
for (int i = 0; i < size; i++) {
// 不分割
dp[k][i] = dp[1][i];
// 看一下怎么分最好(这里只是最多可以切k刀,没代表一定要切k刀)
for (int j = i; j < size-1; j++) {
dp[k][i] = max(dp[k][i], avg[i][j]+dp[k-1][j+1]);
}
}
}
return dp[K][0];
}
};
思路:这道题有一点难度,这道题说是至多K次而不是一定要分K次,所以K循环,每次分或者不分都可以。还有一个技巧就是要学会用dp的一个维度表示A[i:]或者A[0:i],好像一般是表示为前者。