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];
    }

猜你喜欢

转载自blog.csdn.net/yaoct/article/details/84402895