Skip to main content
Back to problems
#813
Medium Algorithms

Largest sum of averages

Array Dynamic Programming Prefix Sum
54.8% acceptance
Feb 22, 2026
2200
104
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.

Solution

Rust
Time O(n³)
Space O(n)
LeetCode
solution.rs
/*
 * 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
 * Constraints:
 * 1 <= nums.length <= 100
 * 1 <= nums[i] <= 104
 * 1 <= k <= nums.length
 */
impl Solution {
  pub fn largest_sum_of_averages(nums: Vec<i32>, k: i32) -> f64 {
    let n = nums.len();
    let k = k as usize;
    let mut prefix = vec![0f64; n + 1];
    for i in 0..n { prefix[i+1] = prefix[i] + nums[i] as f64; }
    // dp[i] = best score partitioned into current groups, using first i elements
    let mut dp = vec![0f64; n + 1];
    for i in 1..=n { dp[i] = prefix[i] / i as f64; } // k=1 base
    for _ in 1..k {
      let mut ndp = vec![0f64; n + 1];
      for i in 1..=n {
        for j in 0..i {
          ndp[i] = ndp[i].max(dp[j] + (prefix[i] - prefix[j]) / (i - j) as f64);
        }
      }
      dp = ndp;
    }
    dp[n]
  }
}