Leetcode题解 813 Largest Sum of Averages 【Dynamic programming】

本文介绍了一种通过动态规划解决的问题:如何将一个数组分成最多K个相邻的非空子数组,使得这些子数组的平均值之和最大。通过示例说明了最优解的选择过程,并提供了详细的AC代码。

摘要生成于 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.

题意分析: 给出一个列表,和一个整数K,将列表分为K部分,求这K个列表的平均值之和的最大值

题目思路: 动态规划, 假设dp[k][j]为将列表[0 : j](闭区间)分为K部分所能得到的平均值之和的最大值,那么dp[k][i] = max(dp[k-1][j]), 其中j属于[k-1, i)


AC代码:

class Solution:
    
    def largestSumOfAverages(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: float
        """
        length = len(A)
        dp = [[0.0 for i in range(length)] for i in range(K)]
        sum_array = [0] * (length+1)
        for i in range(1, length+1):
            sum_array[i] = sum_array[i-1] + A[i-1]

        for i in range(length):
            dp[0][i] = sum_array[i+1]/(i+1)

        for k in range(1, K):
            for i in range(k, length):
                for j in range(k-1, i):
                    dp[k][i] = max(dp[k][i], dp[k-1][j] + \
                               (sum_array[i+1] - sum_array[j+1])/(i-j))

        return dp[K-1][length-1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值