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.
1import java.util.*;
2
3public class LargestSumOfAverages {
4 public double largestSumOfAverages(int[] nums, int k) {
5 int n = nums.length;
6 double[] prefix_sum = new double[n + 1];
7 double[][] dp = new double[n][k];
8
9 for (int i = 0; i < n; ++i) {
10 prefix_sum[i + 1] = prefix_sum[i] + nums[i];
11 }
12
13 for (int i = 0; i < n; ++i) {
14 dp[i][0] = (prefix_sum[n] - prefix_sum[i]) / (n - i);
15 }
16
17 for (int m = 1; m < k; ++m) {
18 for (int i = 0; i < n; ++i) {
19 for (int j = i + 1; j < n; ++j) {
20 dp[i][m] = Math.max(dp[i][m], (prefix_sum[j] - prefix_sum[i]) / (j - i) + dp[j][m - 1]);
21 }
22 }
23 }
24
25 return dp[0][k - 1];
26 }
27
28 public static void main(String[] args) {
29 LargestSumOfAverages solution = new LargestSumOfAverages();
30 int[] nums = {9, 1, 2, 3, 9};
31 int k = 3;
32 System.out.printf("%.5f\n", solution.largestSumOfAverages(nums, k));
33 }
34}
Similar to C++ implementation, this Java solution makes use of arrays to store prefix sums and dynamic programming table results. The method iteratively evaluates different subarray partitions to find the maximum sum of averages.
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.