leetcode 813. Largest Sum of Averages(最大平均数)

本文介绍了一种通过动态规划解决的最大平均分组算法,旨在将一个整数数组分成指定数量的子组,使得这些子组的平均数之和达到最大。

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

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
直接想的话,比如[9,1,2,3,9]分成3组,那就一个一个试,
可以把[9,1,2,3]分2组,最后一个[9]一组,或者[9,1,2]分2组,[3,9]一组,或者[9,1]分2组,[2,3,9]一组

这时候就需要递推了,比如把[9,1,2,3]分2组,最后一个[9]一组,那下一步[9,1,2,3]就需要(1) [9,1,2]一组,3一组,或者(2) [9,1]一组,[2,3]一组,或者(3) [9]一组,[1,2,3]一组,而可以看到,当分成一组的时候,只需要求组内平均数即可。求(1)(2)(3)中较大的平均数,可得[9,1,2,3]分2组的最大平均和。

定义dp[k][i]为0~i的部分分成k组的最大平均和,
那问题又可分解为0~j 分成k-1组,j+1 ~ i分成一组,
即dp[k][i] = dp[k-1][j] + average(j+1 ~ i)
其中average可提前求累加和数组sum, 用(sum[i] - sum[j]) / (i - j)即可

0~i的部分分成k组,那么i至少要为k-1,i = k-1 ~ n-1
0~j的部分分成k-1组,j至少要为k-2, j = k-2 ~ i-1
当k=1时,直接求平均数即可

    public double largestSumOfAverages(int[] A, int K) {
        if(A == null || A.length == 0) {
            return 0;
        }
        
        int n = A.length;
        double[][] dp = new double[K+1][n];
        int[] sum = new int[n];
        sum[0] = A[0];
        dp[1][0] = A[0];
        
        for(int i = 1; i < n; i++) {
            sum[i] = sum[i-1] + A[i];
            dp[1][i] = (double)sum[i] / (i+1);
        }
        
        //0~j 分成k-1组,j~i分成1组, O(kn^2)
        for(int k = 2; k <= K; k++) {
            for(int i = k-1; i < n; i++) {
                for(int j = k-2; j < i; j++){
                //后面平均数要cast到double,不然会截断后再自动cast到double,得不到想要的结果
                    dp[k][i] = Math.max(dp[k][i], dp[k-1][j] + (double)(sum[i] - sum[j])/(i-j));
                }
            }
        }
        return dp[K][n-1];
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值