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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/11452314.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值