zoukankan      html  css  js  c++  java
  • 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: DFS + Memory. [Java]

    class Solution {
        public double largestSumOfAverages(int[] A, int K) {
            int n = A.length;
            double[][] memo = new double[K+1][n+1];
            double[] sum = new double[n+1];
            for (int i = 1; i <= n; ++i) 
                sum[i] += sum[i-1] + A[i-1];
            return LSA(n, K, memo, sum);
            
        }
        
        public double LSA(int n, int k, double[][] memo, double[] sum) {
            if (memo[k][n] > 0) return memo[k][n];
            if (k == 1) return sum[n] / n;
            for (int i = k - 1; i < n; ++i) {
                memo[k][n] = Math.max(memo[k][n], LSA(i, k-1, memo, sum) + (sum[n] - sum[i]) / (n - i));
            }
            return memo[k][n];
        }
    }
    

      

    Approach #2: DP. [C++]

    class Solution {
    public:
        double largestSumOfAverages(vector<int>& A, int K) {
            int n = A.size();
            vector<vector<double>> dp(K+1, vector<double>(n+1, 0.0));
            vector<double> sum(n+1, 0.0);
            for (int i = 1; i <= n; ++i) {
                sum[i] = sum[i-1] + A[i-1];
                dp[1][i] = static_cast<double>(sum[i]) / i;
            }
            
            for (int k = 2; k <= K; ++k)
                for (int i = k; i <= n; ++i) 
                    for (int j = k-1; j < i; ++j)
                        dp[k][i] = max(dp[k][i], dp[k-1][j] + (sum[i] - sum[j]) / (i - j));
            
            return dp[K][n];
        }
    };
    

      

    Refernce:

    http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-813-largest-sum-of-averages/

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    C++中的结构体
    C++转换
    C++常见问题解答
    hdu 1491
    hdu 1253
    [恢]hdu 2529
    [恢]hdu 2539
    hdu 1708
    [恢]hdu 2512
    [恢]hdu 2401
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10573318.html
Copyright © 2011-2022 走看看