Problem 410

Abstract / Summary

Given a list of numbers and a maximum number of splits, find the smallest possible largest sum of any split.

Note

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

Python 0410.py

class Solution:
    def splitArray(self, nums: List[int], k: int) -> int:
        @cache
        def deeper(start, parts):
            if start + parts > len(nums):
                return 999999999999
            if parts == 1:
                return sum(nums[start:])

            best = 999999999999
            current = 0
            for i in range(start, len(nums)):
                current += nums[i]
                score = max(current, deeper(i + 1, parts - 1))
                best  = min(best, score)
            return best

        return deeper(0, k)
18 lines | 582 bytes | submitted September 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 60% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Dynamic Programming
  • Greedy
  • 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 classic “split array largest sum” problem using a top-down recursive strategy with memoization. The splitArray method receives an integer list nums and an integer k, representing the number of sub-arrays into which nums must be partitioned. The goal is to minimize the maximum sum among the k sub-arrays. The core of the solution is the nested deeper function, which explores all feasible split positions while caching intermediate results to avoid redundant computation.

Core Recursive Function

The deeper function is defined with two parameters: start, the index at which the current segment begins, and parts, the number of sub-arrays still required. The function returns the minimal possible largest sum for the segment nums[start:] when it must be divided into parts pieces.

@cache
def deeper(start, parts):
    if start + parts > len(nums):
        return 999999999999
    if parts == 1:
        return sum(nums[start:])
    # ...

Base Cases

The first conditional checks whether the remaining length of the array is insufficient to allocate at least one element per required part (start + parts > len(nums)). In such a scenario the function returns a very large sentinel value, effectively discarding this branch from consideration.

The second conditional handles the situation where only a single part remains (parts == 1). In this case the function returns the sum of all elements from start to the end of the list, because the entire remainder must form the final sub-array.

Exploration Loop

When neither base case applies, the function iterates over possible split points, progressively accumulating the sum of the current left segment (current). For each candidate split at index i, it computes the larger of two quantities: the sum of the left segment (current) and the optimal result of recursively splitting the remainder (deeper(i + 1, parts - 1)). The minimal such maximum across all split positions is retained as best.

best = 999999999999
current = 0
for i in range(start, len(nums)):
    current += nums[i]
    score = max(current, deeper(i + 1, parts - 1))
    best = min(best, score)
return best

Edge Cases Handled

The algorithm explicitly guards against attempts to create more parts than there are elements left, using the start + parts > len(nums) check. This prevents index errors and ensures that each recursive call respects the constraint that every part must contain at least one element.

When k equals the length of nums, the recursion quickly reaches the parts == 1 base case for each element, yielding the maximum element as the answer, which is the correct minimal largest sum for this extreme partitioning.

If k is one, the function bypasses the loop entirely and returns the total sum of the array, matching the expectation that the whole array forms a single sub-array.

The sentinel value 999999999999 is sufficiently large to dominate any realistic sum of the input, guaranteeing that infeasible partitions are never selected as optimal.

Performance Optimizations

Memoization is introduced through the @cache decorator, which stores the result of each (start, parts) pair. This eliminates exponential recomputation by ensuring that each distinct sub-problem is solved at most once.

The early exit condition (start + parts > len(nums)) prunes branches that cannot possibly satisfy the partition requirement, reducing the number of recursive calls explored.

Within the loop, the running total current is updated incrementally rather than recomputed from scratch for each split point, saving repeated summation work.

The use of max and min functions to compare the current segment sum with the recursive result, and to track the best candidate, respectively, provides a concise and efficient way to propagate the optimal value upward through the recursion stack.

Final Return

The public method splitArray initiates the recursion with the full array starting at index 0 and the required number of parts k. The result of this call is the minimal possible largest sum across all valid partitions.

return deeper(0, k)
written by openai gpt

ELI5 - Simplified Explanation

Imagine a long train of numbered toy cars that need to be put into a certain number of boxes. There is a rule that the cars in each box must stay in the same order they are in the line. The goal is to figure out a way to group these cars so that the box with the most weight inside is as light as possible.

The code starts by looking at the very first car and trying to decide how many should go into the first box. It tries every possible way to make that first group, starting with just one car and adding more one by one. For every choice, it asks a helper function to figure out the best way to sort the rest of the cars into the remaining boxes.

Because there are many ways to group the cars, the helper function uses a special trick to remember the answers it has already figured out. This stops it from doing the same hard work over and over again. As it goes through the line, it keeps track of the smallest maximum weight it finds. Once it has looked at all the different ways to pack the cars, it knows exactly which plan keeps the busiest box as light as it can be.

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 = 6 | μ = 6.07 | σ = 1.63

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fpdjsns C++
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
vli02 C
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fpdjsns C++
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
vli02 C
wisdompeak C++
zfang399 C++
38 links | 24 authors | 9 languages

Videos

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

Similar Problems

3 similar problems

Solved On The Same Day

2 easy 6 medium 1 hard
10 solutions   September 19, 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