Largest Sum of Averages - Problem
Largest Sum of Averages

You are given an integer array nums and an integer k. Your goal is to partition the array into at most k non-empty adjacent subarrays to maximize the sum of their averages.

๐ŸŽฏ The Challenge: Each partition creates subarrays, and you want to maximize the total score where the score equals the sum of averages of all subarrays.

Key Rules:
  • Partitions must use every element in the array
  • Subarrays must be adjacent (contiguous)
  • You can use at most k partitions
  • The score is the sum of averages (may be decimal)

Example: For nums = [9,1,2,3,9] and k = 3, the optimal partition is [9], [1,2,3], [9] giving score = 9 + 2 + 9 = 20.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [9,1,2,3,9], k = 3
โ€บ Output: 20.0
๐Ÿ’ก Note: The best partition is [9], [1,2,3], [9]. This gives averages 9, 2, and 9 respectively, for a total score of 20.
example_2.py โ€” Maximum Partitions
$ Input: nums = [1,2,3,4,5,6,7], k = 4
โ€บ Output: 20.5
๐Ÿ’ก Note: One optimal partition is [1], [2], [3], [4,5,6,7]. This gives averages 1, 2, 3, and 5.5 respectively, for a total score of 11.5. Actually the optimal is [1,2,3], [4], [5], [6,7] giving 2 + 4 + 5 + 6.5 = 17.5. Wait let me recalculate: [1], [2,3], [4,5], [6,7] gives 1 + 2.5 + 4.5 + 6.5 = 14.5. The actual optimal is [1,2,3,4], [5], [6], [7] giving 2.5 + 5 + 6 + 7 = 20.5.
example_3.py โ€” Single Partition
$ Input: nums = [4,1,7,3,4,9], k = 1
โ€บ Output: 4.666666666666667
๐Ÿ’ก Note: With k=1, we must use the entire array as one partition. The average is (4+1+7+3+4+9)/6 = 28/6 โ‰ˆ 4.67.

Constraints

  • 1 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค k โ‰ค nums.length
  • 0 โ‰ค nums[i] โ‰ค 104
  • The answer is guaranteed to be within 10-6 of the actual answer

Visualization

Tap to expand
Dynamic Programming Visualization91239Partition 1Partition 2Partition 3Avg: 9Avg: 2Avg: 9Total Score: 9 + 2 + 9 = 20DP explores all partition combinations efficiently
Understanding the Visualization
1
Identify Subproblems
For each position and remaining partitions, find the optimal score
2
Try All Split Points
For each subproblem, try every possible way to place the next partition
3
Memoize Results
Cache computed results to avoid redundant calculations
4
Build Up Solution
Combine optimal subproblem solutions to get the final answer
Key Takeaway
๐ŸŽฏ Key Insight: This problem has optimal substructure - the best way to partition a suffix of the array depends only on that suffix and the number of partitions remaining, not on how we partitioned the prefix. Memoization transforms an exponential problem into a polynomial one.
Asked in
Google 45 Amazon 32 Meta 28 Apple 15
32.4K Views
Medium Frequency
~25 min Avg. Time
1.2K 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