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语言的AES加密
    curl指定域名的IP
    gdb调试知识
    C++获取寄存器eip的值
    C++嵌入lua
    [置顶] python字典和nametuple互相转换例子
    【python】redis基本命令和基本用法详解
    xshell登录到CentOS7上时出现“The remote SSH server rejected X11 forwarding request.
    selinue引起的ssh连接错误
    SCP和SFTP相同点和区别
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10573318.html
Copyright © 2011-2022 走看看