[leetcode]813. Largest Sum of Averages

162 篇文章 0 订阅
23 篇文章 0 订阅

[leetcode]813. Largest Sum of Averages


Analysis

药不能停—— [每天刷题并不难0.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.
在这里插入图片描述

Explanation:

动态规划解决,状态转移方程为DP=DP[k-1][j]+(double)(sum[i]-sum[j])/(i-j).

Implement

class Solution {
public:
    double largestSumOfAverages(vector<int>& A, int K) {
        if(A.empty() || K==0)
            return 0;
        int len = A.size();
        vector<vector<double>> DP(K+1, vector<double>(len, 0));
        vector<int> sum(len);
        sum[0] = A[0];
        for(int i=1; i<len; i++)
            sum[i]=A[i]+sum[i-1];
        for(int k=1; k<=K; k++){
            for(int i=k-1; i<len; i++){
                if(k == 1)
                    DP[k][i] = (double)sum[i]/(i+1);
                else{
                    for(int j=k-2; j<i; j++)
                        DP[k][i] = max(DP[k][i], DP[k-1][j]+(double)(sum[i]-sum[j])/(i-j));
                }
            }
        }
        return DP[K][len-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值