|
| 1 | +/** |
| 2 | + * 813. Largest Sum of Averages |
| 3 | + * https://leetcode.com/problems/largest-sum-of-averages/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer array nums and an integer k. You can partition the array into at most |
| 7 | + * k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each |
| 8 | + * subarray. |
| 9 | + * |
| 10 | + * Note that the partition must use every integer in nums, and that the score is not necessarily |
| 11 | + * an integer. |
| 12 | + * |
| 13 | + * Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 |
| 14 | + * of the actual answer will be accepted. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number[]} nums |
| 19 | + * @param {number} k |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var largestSumOfAverages = function(nums, k) { |
| 23 | + const prefixSum = new Array(nums.length + 1).fill(0); |
| 24 | + for (let i = 0; i < nums.length; i++) { |
| 25 | + prefixSum[i + 1] = prefixSum[i] + nums[i]; |
| 26 | + } |
| 27 | + |
| 28 | + const dp = new Array(nums.length).fill(0).map(() => new Array(k + 1).fill(0)); |
| 29 | + |
| 30 | + for (let i = 0; i < nums.length; i++) { |
| 31 | + dp[i][1] = calculateAverage(i, nums.length - 1); |
| 32 | + } |
| 33 | + |
| 34 | + for (let partitions = 2; partitions <= k; partitions++) { |
| 35 | + for (let start = 0; start < nums.length - partitions + 1; start++) { |
| 36 | + for (let end = start; end < nums.length - partitions + 1; end++) { |
| 37 | + dp[start][partitions] = Math.max( |
| 38 | + dp[start][partitions], |
| 39 | + calculateAverage(start, end) + dp[end + 1][partitions - 1] |
| 40 | + ); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return dp[0][k]; |
| 46 | + |
| 47 | + function calculateAverage(i, j) { |
| 48 | + return (prefixSum[j + 1] - prefixSum[i]) / (j - i + 1); |
| 49 | + } |
| 50 | +}; |
0 commit comments