Skip to content

Instantly share code, notes, and snippets.

@s4553711
Created April 11, 2018 15:22
Show Gist options
  • Save s4553711/5f746c6e0925d73846ee275d609edde9 to your computer and use it in GitHub Desktop.
Save s4553711/5f746c6e0925d73846ee275d609edde9 to your computer and use it in GitHub Desktop.
class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
// const int n = A.size();
// vector<vector<double>> dp(K+1, vector<double>(n+1, 0.0));
// vector<double> sum(n+1, 0.0);
// for(int i = 1; i <= n; i++) {
// sum[i] = sum[i-1] + A[i-1];
// dp[1][i] = static_cast<double>(sum[i]) / i;
// }
// for(int k = 2; k <= K; k++) {
// for(int i = k; i <= n; i++) {
// for(int j = k-1 ; j < i; j++) {
// dp[k][i] = max(dp[k][i], dp[k-1][j] + (sum[i] + sum[j])/(i - j));
// }
// }
// }
// return dp[K][n];
const int n = A.size();
vector<vector<double>> dp(K + 1, vector<double>(n + 1, 0.0));
vector<double> sums(n + 1, 0.0);
for (int i = 1; i <= n; ++i) {
sums[i] = sums[i - 1] + A[i - 1];
dp[1][i] = static_cast<double>(sums[i]) / i;
}
for (int k = 2; k <= K; ++k)
for (int i = k; i <= n; ++i)
for (int j = k - 1; j < i; ++j)
dp[k][i] = max(dp[k][i], dp[k - 1][j] + (sums[i] - sums[j]) / (i - j));
return dp[K][n];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment