# 813. Largest Sum of Averages

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.

dp[i][k] = max(avg(i, n) + max_{j > i} (avg(i, j) + dp[j][k-1]))

``````class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
int n = A.size();
vector<double> sums(n + 1);
vector<vector<double>> dp(n, vector<double>(K));
for (int i = 0; i < n; ++i) {
sums[i + 1] = sums[i] + A[i];
}
for (int i = 0; i < n; ++i) {
dp[i][0] = (sums[n] - sums[i]) / (n - i);
}
for (int k = 1; k < K; ++k) {
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
dp[i][k] = max(dp[i][k], (sums[j] - sums[i]) / (j - i) + dp[j][k - 1]);
}
}
}
return dp[0][K - 1];
}
};
``````

``````class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
int n = A.size();
vector<double> sums(n + 1);
vector<double> dp(n);
for (int i = 0; i < n; ++i) {
sums[i + 1] = sums[i] + A[i];
}
for (int i = 0; i < n; ++i) {
dp[i] = (sums[n] - sums[i]) / (n - i);
}
for (int k = 1; k < K; ++k) {
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
dp[i] = max(dp[i], (sums[j] - sums[i]) / (j - i) + dp[j]);
}
}
}
return dp[0];
}
};
``````

``````class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
int n = A.size();
vector<vector<double>> memo(101, vector<double>(101));
double cur = 0;
for (int i = 0; i < n; ++i) {
cur += A[i];
memo[i + 1][1] = cur / (i + 1);
}
return helper(A, K, n, memo);
}
double helper(vector<int>& A, int k, int j, vector<vector<double>>& memo) {
if (memo[j][k] > 0) return memo[j][k];
double cur = 0;
for (int i = j - 1; i > 0; --i) {
cur += A[i];
memo[j][k] = max(memo[j][k], helper(A, k - 1, i, memo) + cur / (j - i));
}
return memo[j][k];
}
};
``````

https://leetcode.com/problems/largest-sum-of-averages/description/

https://leetcode.com/problems/largest-sum-of-averages/solution/

https://leetcode.com/problems/largest-sum-of-averages/discuss/122739/C++JavaPython-Easy-Understood-Solution-with-Explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation