zoukankan      html  css  js  c++  java
  • leetcode813 Largest Sum of Averages

     1 """
     2 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?
     3 Note that our partition must use every number in A, and that scores are not necessarily integers.
     4 Example:
     5 Input:
     6 A = [9,1,2,3,9]
     7 K = 3
     8 Output: 20
     9 Explanation:
    10 The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
    11 We could have also partitioned A into [9, 1], [2], [3, 9], for example.
    12 That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
    13 """
    14 """
    15 这题目的思想是基于一个事实:一个数组分割之后肯定是份数越多得到的平均值就越大。
    16 我们假设dp[i][k]表示为数组A【0~i】分割k份得到的最大平均值。
    17 因为最后一个分割点可以出现在任何部分(实际上也得出现在大于k-1个位置之后),所以
    18 dp[i][k]=max(dp[i][k], dp[j][k-1]+sum(j~i)/(i-j)) 其中j在j之前的地方j<i,
    19 因此可以把这个递推式理解为重新选择最后一个分割点的最大处。
    20 当然,要迅速完成sum段求和还需要一个小函数。
    21 传送门:https://blog.csdn.net/weixin_37373020/article/details/81543069
    22 """
    23 class Solution:
    24     def largestSumOfAverages(self, A, K):
    25         sums = [0]
    26         for a in A:
    27             sums.append(sums[-1]+a) #sums[i] = A[0]+A[1]+...A[i-1]
    28         def gap_sum(i, j):
    29             return sums[j]-sums[i]
    30         dp = [[0 for x in range(K+1)] for y in range(len(A)+1)]
    31         for i in range(1, len(A)+1):
    32             dp[i][1] = gap_sum(0, i)/i
    33         for k in range(2, K+1):
    34             for i in range(k, len(A)+1):
    35                 for j in range(i):
    36                     dp[i][k] = max(dp[i][k], dp[j][k-1]+gap_sum(j, i)/(i-j))
    37         return dp[len(A)][K]
  • 相关阅读:
    Oracle错误一览表
    Oracle的基本操作
    oracle 从select的结果update其他表
    生成注册码的一种算法
    ASP.NET程序中常用的三十三种代码
    C# 中获取CPU序列号/网卡mac地址
    C# 断点续传原理与实现
    Cache与主存地址映像计算例题
    javac命令
    VS2010快捷键大全
  • 原文地址:https://www.cnblogs.com/yawenw/p/12319182.html
Copyright © 2011-2022 走看看