813. Largest Sum of Averages

We partition a row of numbersA into at mostKadjacent (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.

tag: DFS, memorization

class Solution {
    public double largestSumOfAverages(int[] A, int K) {
        int len = A.length;
        double[] sum = new double[len];

        sum[0] = A[0];
        for(int i = 1;i < len;i++)  sum[i] += sum[i - 1] + A[i];

        return backTrack(A, len, sum, 0, K, new double[len][K + 1]);
    }
    public double backTrack(int[] A, int len, double[] sum, int index, int K, double[][] dp){
        if(K == 1)              return (sum[len - 1] - sum[index] + A[index]) / (len - index);
        if(dp[index][K] != 0)   return dp[index][K];

        for(int i = index;i <= len - K;i++){
            dp[index][K] = Math.max(dp[index][K], (((sum[i] - sum[index] + A[index]) * 1.0) / (i - index + 1)) + backTrack(A, len, sum, i + 1, K - 1, dp));
        }

        return dp[index][K];
    }
}

results for ""

    No results matching ""