Largest Sum of Averages - Problem

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.

Input & Output

Example 1 — Basic Partitioning
$ Input: nums = [9,1,2,3], k = 3
Output: 13.5
💡 Note: Best partition is [9], [1,2], [3] with averages 9 + 1.5 + 3 = 13.5.
Example 2 — Single Partition
$ Input: nums = [1,2,3,4,5,6,7], k = 4
Output: 20.83333
💡 Note: With k=4 partitions allowed, we can split into groups like [1],[2,3],[4,5],[6,7] giving averages 1 + 2.5 + 4.5 + 6.5 = 14.5, or try other combinations to maximize the sum of averages.
Example 3 — No Partitioning Needed
$ Input: nums = [4,1,7,9], k = 1
Output: 5.25
💡 Note: With k=1, we must use the entire array as one partition: [4,1,7,9] with average (4+1+7+9)/4 = 21/4 = 5.25.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ k ≤ nums.length
  • 0 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Largest Sum of Averages INPUT Array nums: 9 i=0 1 i=1 2 i=2 3 i=3 k = 3 partitions Goal: Partition into at most k subarrays to maximize sum of averages Input Values: nums = [9, 1, 2, 3] k = 3 ALGORITHM STEPS 1 Define DP State dp[i][j] = max score for first i elements, j parts 2 Base Case dp[i][1] = avg(nums[0..i]) Single partition average 3 Transition dp[i][j] = max over all m: dp[m][j-1] + avg(m+1..i) 4 Find Maximum Answer = max(dp[n][j]) for j from 1 to k Optimal Partition: [9] [1] [2,3] 9 + 1 + 2.5 = 12.5? Try others [9]+[1]+[2]+[3] not valid (k=3) FINAL RESULT Optimal Partition Found: [9] avg = 9 [1] avg = 1 [2, 3] avg = 2.5 Wait - let's recalculate: Best: [9] + [1,2,3]? k=2 9 + 2 = 11 Best k=3: [9]+[1]+[2,3] 9 + 1 + 2.5 = 12.5 Optimal: [9,1]+[2]+[3] 5 + 2 + 3 = 10... hmm [9]+[1]+[2]+[3] if k allows Output: 20.0 Key Insight: This is a classic DP problem. For k=3 with [9,1,2,3], the optimal partition is actually [9] + [1] + [2] + [3] = 9+1+2+3 = 15 if k=4. With k=3: we need DP to find that keeping single elements maximizes score. Answer 20.0 = 9 + 1 + 2 + 3 + 5 (from larger groups). Use DP transition carefully! TutorialsPoint - Largest Sum of Averages | Dynamic Programming Approach
Asked in
Google 15 Facebook 12 Amazon 8
35.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen