Problem 813

Abstract / Summary

Given a list of numbers and a limit on how many parts to split them into, find the maximum sum of averages of those parts.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
19 lines | 600 bytes | submitted October 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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
  • pos marks the start index of the sub-array currently being considered.
  • parts indicates 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
  • have holds the running total of the current segment, allowing the average to be computed in constant time per iteration.
  • avg is the average of the segment nums[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.
  • best tracks 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.67 | σ = 1.36

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
28 links | 16 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

3 easy 7 medium 1 hard
12 solutions   October 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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