LeetCode 813. Largest Sum of Averages

原题链接在这里:https://leetcode.com/problems/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.

题解:

Let dp[k][i] denotes largest sum of averages of A up to index i in to k adjacent parts.

For j from k-1 to i, separate them into 2 sections, first k-1 parts from k-1 to j, second 1 part from j to i.

Then dp[k][i] = max(dp[k-1][j] + ave(j-i)).

可以降维.

Time Complexity: O(k*n^2). n = A.length.

Space: O(k*n). 

AC Java: 

 1 class Solution {
 2     public double largestSumOfAverages(int[] A, int K) {
 3         if(A == null || A.length == 0){
 4             return 0;
 5         }
 6         
 7         int n = A.length;
 8         double [] sum = new double[n+1];
 9         double [][] dp = new double[K+1][n+1];
10         for(int i = 1; i<=n; i++){
11             sum[i] = sum[i-1]+A[i-1];
12             dp[1][i] = sum[i]/i;
13         }
14         
15         for(int k = 2; k<=K; k++){
16             for(int i = k; i<=n; i++){
17                 for(int j = k-1; j<i; j++){
18                     dp[k][i] = Math.max(dp[k][i], dp[k-1][j]+(sum[i]-sum[j])/(i-j));
19                 }
20             }
21         }
22         
23         return dp[K][n];
24     }
25 }

 

posted @ 2019-09-03 12:43  Dylan_Java_NYC  阅读(348)  评论(0编辑  收藏  举报