[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];
}
};

本文解析了LeetCode上编号为813的问题“最大平均数和”,通过动态规划的方法解决了将一组数字划分成最多K个连续子组以获得最大总平均值的挑战。详细介绍了状态转移方程和实现代码。
2549

被折叠的 条评论
为什么被折叠?



