1. 程式人生 > >leetcode 813. Largest Sum of Averages

leetcode 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方法解決。最後一個分割的點把問題分成子問題,分割點左邊的子串也是最佳分割。dp[i][j]代表第i次分割,前j個字元子串 的解。因為最後一次分割要遍歷 子串,多了一維時間複雜度。時間複雜度O(KN^2)。

    public double largestSumOfAverages(int[] A, int K) {
        double[][] dp=new double[K][A.length];
        double sum=0;
        for(int j=0;j<A.length;j++){
            sum+=A[j];
            dp[0][j]=sum/(j+1);
        }
        for(int i=1;i<K;i++){
            for(int j=0;j<A.length;j++){
                sum=0;
                for(int k=j;k>=0;k--){
                    sum+=A[k];
                    dp[i][j]=Math.max(dp[i][j],(k==0?0:dp[i-1][k-1])+sum/(j-k+1));
                }
            }
        }
        return dp[K-1][A.length-1];
    }