Leetcode•Jul 01, 2026
Largest Sum of Averages
Hazrat Ali
Leetcode
You are given an integer array nums and an integer k. You can partition the array into at most k non-empty adjacent subarrays. The score of a partition is the sum of the averages of each subarray.
Note that the partition must use every integer in nums, and that the score is not necessarily an integer.
Return the maximum score you can achieve of all the possible partitions. Answers within 10-6 of the actual answer will be accepted.
Example 1:
Input: nums = [9,1,2,3,9], k = 3 Output: 20.00000 Explanation: The best choice is to partition nums into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20. We could have also partitioned nums into [9, 1], [2], [3, 9], for example. That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Example 2:
Input: nums = [1,2,3,4,5,6,7], k = 4 Output: 20.50000
Solution
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var largestSumOfAverages = function(nums, k) {
const n = nums.length;
const prefix = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + nums[i];
}
let dp = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
dp[i] = (prefix[n] - prefix[i]) / (n - i);
}
for (let p = 2; p <= k; p++) {
const next = [...dp];
for (let i = 0; i < n; i++) {
for (let j = i + 1; j <= n; j++) {
const avg = (prefix[j] - prefix[i]) / (j - i);
next[i] = Math.max(next[i], avg + dp[j]);
}
}
dp = next;
}
return dp[0];
};