[leetcode]813. Largest Sum of Averages
Analysis
药不能停—— [每天刷题并不难0.0]
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.
Explanation:
动态规划解决,状态转移方程为DP=DP[k-1][j]+(double)(sum[i]-sum[j])/(i-j).
Implement
class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
if(A.empty() || K==0)
return 0;
int len = A.size();
vector<vector<double>> DP(K+1, vector<double>(len, 0));
vector<int> sum(len);
sum[0] = A[0];
for(int i=1; i<len; i++)
sum[i]=A[i]+sum[i-1];
for(int k=1; k<=K; k++){
for(int i=k-1; i<len; i++){
if(k == 1)
DP[k][i] = (double)sum[i]/(i+1);
else{
for(int j=k-2; j<i; j++)
DP[k][i] = max(DP[k][i], DP[k-1][j]+(double)(sum[i]-sum[j])/(i-j));
}
}
}
return DP[K][len-1];
}
};