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++ isdigit函数
    c++ swap函数
    1.2Hello, World!的大小
    1.2整型与布尔型的转换
    1.2打印ASCII码
    leetcode[170]Two Sum III
    leetcode[167]Two Sum II
    leetcode[1]Two Sum
    leetcode[2]Add Two Numbers
    leetcode[3]Longest Substring Without Repeating Characters
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10573318.html
Copyright © 2011-2022 走看看