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)
Difficulty
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
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 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) 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.
Code Quality
Complexity Analysis
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
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++ | 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++ |
Videos
Similar Problems
- problem 1011: Capacity To Ship Packages Within D Days
- problem 2234: Maximum Total Beauty of the Gardens
- problem 2547: Minimum Cost to Split an Array
Solved On The Same Day
- problem 566: Reshape the Matrix
- problem 594: Longest Harmonious Subsequence
- problem 324: Wiggle Sort II
- problem 386: Lexicographical Numbers
- problem 388: Longest Absolute File Path
- problem 390: Elimination Game
- problem 406: Queue Reconstruction by Height
- problem 491: Non-decreasing Subsequences
- problem 472: Concatenated Words
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