【LeetCode 813】 Largest Sum of Averages

本文探讨了一个有趣的问题:如何将一组数字划分为最多K个相邻的非空子集,使得每个子集的平均值之和最大。通过动态规划的方法,我们找到了解决这一问题的有效途径。

题目描述

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.

思路

dp[i][k] 表示从 0 到 i 前 i+1 个元素,分成k组,平均值之和的最大值。
遍历数组,对于前i个元素,遍历 k-1和k的划分位置j, dp[i][k] = max(dp[i][k], dp[j-1][k-1]+avg(j, i)) ,找的最大值。

这个思路好像做过。。
一看就会,一做就不会。。
什么情况。。。

代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值