Sponsored
Sponsored
This approach utilizes dynamic programming combined with prefix sums to efficiently calculate the sum of subarray averages when partitioned optimally. The prefix sum array allows for quick computation of subarray sums, and dynamic programming is used to build the optimal solution up to k partitions.
Time Complexity: O(n^2 * k), where n is the length of the array, and k is the number of partitions.
Space Complexity: O(n * k) due to the dp table.
1#include <vector>
2#include <iostream>
3#include <algorithm>
4
5using namespace std;
6
7double largestSumOfAverages(vector<int>& nums, int k) {
8 int n = nums.size();
9 vector<double> prefix_sum(n + 1, 0);
10 vector<vector<double>> dp(n, vector<double>(k, 0));
11
12 for (int i = 0; i < n; ++i) {
13 prefix_sum[i + 1] = prefix_sum[i] + nums[i];
14 }
15
16 for (int i = 0; i < n; ++i) {
17 dp[i][0] = (prefix_sum[n] - prefix_sum[i]) / (n - i);
18 }
19
20 for (int m = 1; m < k; ++m) {
21 for (int i = 0; i < n; ++i) {
22 for (int j = i + 1; j < n; ++j) {
23 dp[i][m] = max(dp[i][m], (prefix_sum[j] - prefix_sum[i]) / (j - i) + dp[j][m - 1]);
24 }
25 }
26 }
27
28 return dp[0][k - 1];
29}
30
31int main() {
32 vector<int> nums = {9, 1, 2, 3, 9};
33 int k = 3;
34 cout << fixed << setprecision(5) << largestSumOfAverages(nums, k) << endl;
35 return 0;
36}
This code implementation follows the same logic as the C version but uses C++ vector for easier management of dynamic arrays. It iterates over possible partitions and leverages prefix sums to calculate subarray averages efficiently.
This approach uses recursion with memoization to solve for the maximum sum of averages by exploring all possible partition strategies and storing computed results for reuse. This avoids redundant computations and optimizes performance compared to plain recursion.
Time Complexity: O(n^2 * k) as each subproblem is solved once.
Space Complexity: O(n * k) for memoization table.
1
The JavaScript version uses a memoization pattern to solve recursive subproblems once and reuse calculated results, keeping track of prefix sums for efficient calculation of subarray averages.