813-Largest Sum of Averages

Description:
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.

问题描述:
我们把数组A分为K个相邻的组,最终分数等于每个组的平均数之和。我们能达到的最大的分数是多少?
需要注意,我们必须用上A的每个数,并且分数不必是整数


问题分析:
回溯法
有两个变量,下标index和K.
我们需要对回溯过程优化,因此维护一个二维数组保存状态
为了进一步优化,预先计算了前缀数组
既然是分组,我的想法就是一段一段的求和
例如[1, 2, 3, 4, 5],它的前缀数组为[1, 3, 6, 10, 15]
若将其分为[1, 2]和[3, 4, 5]两份
那么通过前缀数组计算十分方便:
result=(31+1)/2+(156+3)/3=5.5 r e s u l t = ( 3 − 1 + 1 ) / 2 + ( 15 − 6 + 3 ) / 3 = 5.5


解法(dfs + memorization):

class Solution {
    public double largestSumOfAverages(int[] A, int K) {
        int len = A.length;

        double[] sum = new double[len];
        sum[0] = A[0];
        //sum为前缀数组,可以提高计算效率
        for(int i = 1;i < len;i++){
            sum[i] += sum[i - 1] + A[i];
        }
        //维护一个二维数组,保存状态
        double[][] dp = new double[len][K + 1];

        return backTrack(A, sum, 0, K, dp);
    }
    public double backTrack(int[] A, double[] sum, int index, int K, double[][] dp){
        if(K == 1){
            return (sum[A.length - 1] - sum[index] + A[index]) / (A.length - index);
        }

        if(dp[index][K] != 0)   return dp[index][K];

        for(int i = index;i <= A.length - K;i++){
            //每往下递归,即开始新的分组,分组的和通过前缀数组来求
            dp[index][K] = Math.max(dp[index][K], (((sum[i] - sum[index] + A[index]) * 1.0) / (i - index + 1)) + backTrack(A, sum, i + 1, K - 1, dp));
        }

        return dp[index][K];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值