Largest Sum of Averages

Description

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.

Solution

class Solution {
public:
    double largestSumOfAverages(vector<int>& A, int K) {
        int n = A.size();
        // dp[k][i]: largest sum of average of A[0..i] with exactly k groups
        vector<vector<double>> dp(K + 1, vector<double>(n));
        vector<int> sums(n + 1);
        for(int i = 0; i < n; ++i){
            sums[i + 1] = sums[i] + A[i];
            dp[1][i] = static_cast<double>(sums[i + 1]) / (i + 1);
        }
        for(int k = 2; k <= K; ++k){
            for(int i = k - 1; i < n; ++i){
                double max_sum = 0;
                for(int j = k - 2; j < i; ++j){
                    double avg = static_cast<double>(sums[i + 1] - sums[j + 1]) / (i - j);
                    max_sum = max(max_sum, avg + dp[k - 1][j]);
                }
                dp[k][i] = max_sum;
            }
        }
        return dp[K][n - 1];
    }
};

Last updated