[WXM] LeetCode 813. Largest Sum of Averages C++

博客围绕将数组 A 最多分成 K 个相邻非空组,求各子数组平均数之和的最大值展开。因 K 随机且大,放弃 DFS 方法,采用递推思想,通过从底往上递推来求解,还提到可打表辅助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Approach

  1. 题目大意就是一个数组切分成K份,然后求每个子数组的平均数然后相加的值最大为多少。这道题本想着DFS,可是K是随机并且也太大了,所以放弃了,然后看了大神的播客,才渐渐明白,用到了递推的思想,首先你要你要求N个数K个分组的情况,那么你就要知道MAX(K个数K-1个分组的平均数+N-K后面的平均数、K+1个数K-1个分组的平均数+N-K-1后面的平均数、K+2个数K-1个分组的平均数+N-K-2后面的平均数、、、、N-1个数K-1个分组的平均数+N-N+1后面的平均数),你要求的这些数值,那么就需要递推,从底往上递推,所以方程dp[i][j] = max(dp[i][j], dp[i - 1][k] + (sum[j] - sum[k]) / (1.0*(j - k))); dp[i][j]表示j个数i个分组平均数最大的值
  2. 其实可以把表打出来更好理解
A = [9,1,2,3,9]
K = 3

K=1    9    5     4       3.75     4.80
K=2    9    10    10.5    11.00    12.75
K=3    9    10    12      13.50    20.00

Code

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值