Leetcode 813. Largest Sum of Averages
You are given an integer array A
and an integer K
. You can partition the array into at most K
non-empty adjacent subarrays, and the score of a partition is the sum of the averages of each subarray. Determine the largest sum of averages you can achieve.
Input: A = [9,1,2,3,9], K = 3
Output: 20
Explanation:
[9], [1, 2, 3], [9]
with the corresponding averages 9
, 2
, and 9
respectively. Hence, the result is 9 + 2 + 9 = 20
.A.length
<= 100A[i]
<= 10000K
<= A.length
K
be larger than the length of the array A
?
K
will always be less than or equal to the length of A
.A[i]
<= 10000.dp[i][k]
as the maximum sum of averages we can achieve for the first i
elements with k
partitions.i
and making a partition at j
, the new state can be derived using dp[j][k-1]
plus the average of subarray [j+1, i]
.#include <vector>
#include <numeric>
#include <iostream>
using namespace std;
class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
int n = A.size();
vector<double> prefixSum(n + 1, 0.0);
for (int i = 0; i < n; ++i) {
prefixSum[i + 1] = prefixSum[i] + A[i];
}
vector<vector<double>> dp(n + 1, vector<double>(K + 1, 0.0));
for (int i = 1; i <= n; ++i) {
dp[i][1] = prefixSum[i] / i;
}
for (int k = 2; k <= K; ++k) {
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
dp[i][k] = max(dp[i][k], dp[j][k - 1] + (prefixSum[i] - prefixSum[j]) / (i - j));
}
}
}
return dp[n][K];
}
};
O(n^2 * K)
, where n
is the length of array A
. This results from three nested loops: the outer loop iterates over K
(partitions), and the two inner loops (one to fix the end of the subarray and one to iterate over possible start points).O(n * K)
, due to the DP table dp
and the prefix sum array.This solution efficiently computes the largest sum of averages by leveraging dynamic programming and prefix sums to reduce redundant calculations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?