813. Largest Sum of Averages

85 篇文章 0 订阅
83 篇文章 0 订阅

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.

题意:


给出一个数组和数字k,将这个数组最多分成k部分,是的每部分的平均数之和最大,求最大值。

思路:

还真的挺难的。。。首先设置数组dp[i,k]表示从i到N拆分k部分,那么dp[i,k]=max(dp[i,k]],dp[j,k-1]+average(i,j)),其中average(i,j)表示从i到j这些数的平均数。对于求average(i,j),可以设置一个数组P[i]表示从i到N这些数的和,就可以方便的求,降低时间复杂度。至于如何降低空间复杂度的,还看不太懂。。。。

代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值