Python 0813.py
class Solution:
def largestSumOfAverages(self, nums: List[int], k: int) -> float:
@cache
def deeper(pos, parts):
remain = len(nums) - pos
if remain == 0:
return 0
if parts == 1:
return sum(nums[pos:]) / remain
best = 0
have = 0
for i in range(pos, len(nums)):
have += nums[i]
avg = have / (i - pos + 1)
best = max(best, avg + deeper(i + 1, parts - 1))
return best
return deeper(0, k)
Difficulty
and has an acceptance rate of about 55% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Prefix Sum
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of partitioning a list of integers into k contiguous groups so that the sum of the averages of those groups is maximized. It does this by defining a recursive helper, deeper, that explores every possible split point while caching intermediate results to avoid redundant work.
Core Logic
The heart of the solution is the nested function deeper(pos, parts).
@cache
def deeper(pos, parts):
remain = len(nums) - pos
if remain == 0:
return 0
if parts == 1:
return sum(nums[pos:]) / remain
posmarks the start index of the sub-array currently being considered.partsindicates how many groups still need to be formed from that sub-array.
When only one group remains (parts == 1), the function returns the average of the entire suffix nums[pos:]. This is the terminating condition for the recursion that does not require further splitting.
If more than one group is required, the function iterates over every possible end index for the first group, accumulates the sum incrementally, computes the average for that segment, and adds the best result of the remaining sub-problem:
best = 0
have = 0
for i in range(pos, len(nums)):
have += nums[i]
avg = have / (i - pos + 1)
best = max(best, avg + deeper(i + 1, parts - 1))
return best
haveholds the running total of the current segment, allowing the average to be computed in constant time per iteration.avgis the average of the segmentnums[pos:i+1].- The recursive call
deeper(i + 1, parts - 1)evaluates the optimal sum of averages for the remainder of the list after the current split. besttracks the maximum combined value found across all split positions.
The outer method simply initiates the recursion with the full array and the required number of groups:
return deeper(0, k)
Edge Cases Handled
When the sub-array length is zero (remain == 0), the function returns 0. This situation occurs only when the recursion reaches the end of the list after having allocated all required groups, ensuring that no extra value is added to the total.
The case parts == 1 guarantees that the algorithm correctly handles the scenario where the remaining elements must form a single group, regardless of how many elements are left. This prevents unnecessary further recursion and directly yields the correct average for the final segment.
The loop runs from the current position to the end of the list, which naturally covers the situation where the first group consumes the entire remaining array. In that case, the recursive call receives pos equal to the length of the list and parts - 1 equal to zero; the base case remain == 0 then returns 0, and the computed avg becomes the sole contribution to the result.
Performance Optimizations
The decorator @cache (from functools) memoizes the results of deeper for each unique pair (pos, parts). Because the same sub-problem can be reached via different split sequences, caching eliminates exponential recomputation and reduces the effective number of distinct calls to the product of the array length and the number of groups.
The incremental accumulation variable have avoids recomputing the sum of the current segment on each iteration. By adding the next element to have instead of calling sum on a slice, the algorithm maintains an O(1) cost per iteration inside the loop.
Together, memoization and incremental sum calculation transform what would be a naïve exponential search into a tractable dynamic-programming approach that explores each feasible split exactly once.
ELI5 - Simplified Explanation
Imagine a long row of numbered blocks sitting on a table. The goal is to chop this line of blocks into a specific number of smaller groups so that the average number inside each group adds up to the biggest score possible.
The code starts by looking at the very first block and deciding where to make the first cut. After making that cut, it creates an average for that first group and then tells a helper function to repeat the process for all the remaining blocks. Because there are many different ways to cut the line, the computer tries every possibility and keeps track of which choices lead to the highest total.
Whenever the helper function encounters a situation it has seen before, it remembers the answer to save time. It continues making these cuts until it reaches the exact number of groups requested. By looking at all the different ways to slice the line, the computer eventually identifies which combination makes the largest total for the averages.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | |||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| gouthampradhan | Java | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 812: Largest Triangle Area
- problem 824: Goat Latin
- problem 844: Backspace String Compare
- problem 791: Custom Sort String
- problem 794: Valid Tic-Tac-Toe State
- problem 807: Max Increase to Keep City Skyline
- problem 814: Binary Tree Pruning
- problem 825: Friends Of Appropriate Ages
- problem 848: Shifting Letters
- problem 849: Maximize Distance to Closest Person
- problem 815: Bus Routes
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality