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.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-sum-of-averages
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

动态规划,dp[i][k]标识从A[i,A.lenght]分成k组的平均值的最大。那么我们就可以把下一个状态,dp[i][k+1] 看成从[i, lenght]中分成两段,前一段的平均值 + 后一段的平均值。

dp[i][k] = max(dp[i][k], (avg(i, j) + dp[j][k-1]))

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

    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值