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.
1def largestSumOfAverages(nums, k):
2 n = len(nums)
3 prefix_sum = [0] * (n + 1)
4 dp = [[0] * k for _ in range(n)]
5
6 for i in range(n):
7 prefix_sum[i + 1] = prefix_sum[i] + nums[i]
8
9 for i in range(n):
10 dp[i][0] = (prefix_sum[n] - prefix_sum[i]) / (n - i)
11
12 for m in range(1, k):
13 for i in range(n):
14 for j in range(i + 1, n):
15 dp[i][m] = max(dp[i][m], (prefix_sum[j] - prefix_sum[i]) / (j - i) + dp[j][m - 1])
16
17 return dp[0][k - 1]
18
19nums = [9, 1, 2, 3, 9]
20k = 3
21print(f'{largestSumOfAverages(nums, k):.5f}')
In Python, lists are used for both prefix sums and dynamic programming table. This code calculates the solution by trying different partitions and choosing the optimal partitioning setup for maximal average sum.
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
public class Solution {
private double[,] memo;
private double[] prefixSum;
private double Solve(int i, int k, int n) {
if (k == 1) return (prefixSum[n] - prefixSum[i]) / (n - i);
if (Math.Abs(memo[i, k] + 1) > 1e-9) return memo[i, k];
double maxScore = 0;
for (int j = i + 1; j <= n - (k - 1); ++j) {
maxScore = Math.Max(maxScore, (prefixSum[j] - prefixSum[i]) / (j - i) + Solve(j, k - 1, n));
}
return memo[i, k] = maxScore;
}
public double LargestSumOfAverages(int[] nums, int k) {
int n = nums.Length;
memo = new double[n, k + 1];
prefixSum = new double[n + 1];
for (int i = 0; i < n; ++i) {
prefixSum[i + 1] = prefixSum[i] + nums[i];
}
for (int i = 0; i < n; ++i)
for (int j = 0; j <= k; ++j)
memo[i, j] = -1;
return Solve(0, k, n);
}
public static void Main() {
int[] nums = {9, 1, 2, 3, 9};
int k = 3;
Solution sol = new Solution();
Console.WriteLine(sol.LargestSumOfAverages(nums, k).ToString("F5"));
}
}
This C# approach uses recursion and memoization for efficient calculation of maximum average sum combinations by maintaining a table of computed results to avoid repetitive calculations in recursive calls.