[WXM] LeetCode 813. Largest Sum of Averages C++

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. 题目大意就是一个数组切分成K份,然后求每个子数组的平均数然后相加的值最大为多少。这道题本想着DFS,可是K是随机并且也太大了,所以放弃了,然后看了大神的播客,才渐渐明白,用到了递推的思想,首先你要你要求N个数K个分组的情况,那么你就要知道MAX(K个数K-1个分组的平均数+N-K后面的平均数、K+1个数K-1个分组的平均数+N-K-1后面的平均数、K+2个数K-1个分组的平均数+N-K-2后面的平均数、、、、N-1个数K-1个分组的平均数+N-N+1后面的平均数),你要求的这些数值,那么就需要递推,从底往上递推,所以方程dp[i][j] = max(dp[i][j], dp[i - 1][k] + (sum[j] - sum[k]) / (1.0*(j - k))); dp[i][j]表示j个数i个分组平均数最大的值
  2. 其实可以把表打出来更好理解
A = [9,1,2,3,9]
K = 3

K=1    9    5     4       3.75     4.80
K=2    9    10    10.5    11.00    12.75
K=3    9    10    12      13.50    20.00

Code

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

你可能感兴趣的:([WXM] LeetCode 813. Largest Sum of Averages C++)