813. Largest Sum of Averages

Question

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:

  • Method 1: dp O(N^3)
    • How to solve this question: dp[k][i] the max result with K spilt for previous i numbers in the array
    • Initialization: dp[1][i] = average(index 0 to index i).
    • Transfer function:
      • dp[k][i] = dp[k - 1][j] + average(from j + 1 to 1)
    • Result: dp[K][length of A]
    • Trick: how to calcualte the average (get the difference between the sum and divided by the length).
        class Solution {
        public double largestSumOfAverages(int[] A, int K) {
            double[][] dp = new double[K + 1][A.length + 1];
            double[] sum = new double[A.length + 1];
            for(int i = 1; i <= A.length; i++){
                sum[i] = sum[i - 1] + A[i - 1];
                dp[1][i] = sum[i] / i;
            }
            for(int k = 2; k <= K; k++){
                for(int i = k; i <= A.length; i++){
                    for(int j = k - 1; j < i; j++){
                        dp[k][i] = Math.max(dp[k - 1][j] + (sum[i] - sum[j]) / (i - j), dp[k][i]);
                    }
                }
            }
            return dp[K][A.length];
        }
        }
      

Reference

  1. 花花酱 LeetCode 813. Largest Sum of Averages