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)
  • 相关阅读:
    .net core 部署到 iis 步骤及报错解决方法
    数据库学习笔记3 基本的查询流 2
    数据库学习笔记 2 数据库文件基本查询
    我对于C#的想法
    数据库学习笔记 一
    openwrt 软件安装依赖冲突
    openwrt 自定义DHCP
    asp.net core 3.1 入口:Program.cs中的Main函数
    c# 匿名方法(函数) 匿名委托 内置泛型委托 lamada
    家庭网络那些事
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10573318.html
Copyright © 2011-2022 走看看