Python 1043.py
class Solution:
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
@cache
def deeper(pos):
if pos >= len(arr):
return 0
best = 0
high = 0
for i in range(k):
index = pos + i
if index >= len(arr):
break
high = max(high, arr[index])
best = max(best, (i + 1) * high + deeper(index + 1))
return best
return deeper(0)
Difficulty
and has an acceptance rate of about 78% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
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 “maximum sum after partitioning” problem using a top-down dynamic programming approach. A recursive helper, deeper, explores every feasible partition that starts at a given position in the input list arr. For each partition length up to k, it computes the contribution of that segment as the product of the segment length and the maximum element inside the segment, then adds the optimal result of the suffix that follows. Memoization via @cache ensures each sub-problem is solved only once, yielding an efficient solution.
Core Logic
The entry point maxSumAfterPartitioning receives the array and the maximum allowed partition size k. It defines the nested function deeper(pos) that returns the best achievable sum for the suffix beginning at index pos. The final answer is obtained by invoking deeper(0).
def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
@cache
def deeper(pos):
...
return deeper(0)
Recursive Exploration
Inside deeper, the base case checks whether the current position has reached or passed the end of the array. In that situation the function returns 0, indicating that no further contribution can be added.
if pos >= len(arr):
return 0
The main loop iterates over possible partition lengths from 1 to k. For each iteration it:
- Computes the absolute index of the element being examined (
index = pos + i). - Stops the loop early if the index exceeds the array bounds, handling the situation where the remaining elements are fewer than
k. - Updates
highto be the maximum value seen in the current window. - Calculates the candidate sum as the size of the window (
i + 1) multiplied byhigh, plus the optimal result of the remainder (deeper(index + 1)). - Keeps the best candidate in
best.
best = 0
high = 0
for i in range(k):
index = pos + i
if index >= len(arr):
break
high = max(high, arr[index])
best = max(best, (i + 1) * high + deeper(index + 1))
return best
Memoization
The decorator @cache (available from functools) automatically stores the result of each distinct call to deeper(pos). When the same position is encountered again, the cached value is returned instantly, eliminating redundant recomputation of overlapping sub-problems. This transformation from exponential recursion to polynomial-time dynamic programming is the primary performance gain.
Edge Cases Handled
When the remaining portion of the array is shorter than k, the loop’s guard if index >= len(arr): break prevents out-of-range access and ensures that partitions are only formed from existing elements. The base case pos >= len(arr) gracefully handles an empty suffix, returning 0 without further processing. These checks together guarantee correct behavior for inputs where len(arr) < k, k == 1, or arr contains a single element.
Performance Optimizations
The combination of a top-down recursion with memoization avoids the overhead of constructing an explicit DP table. Because each index pos is evaluated at most once, the algorithm’s work is proportional to the number of positions multiplied by the bounded loop of size k. The use of local variables best and high inside the loop minimizes attribute lookups and keeps the inner computation tight. Early termination of the loop when the array end is reached reduces unnecessary iterations, especially for the final few positions. The reliance on Python’s built-in max function for updating high and best leverages highly optimized C-level code, further speeding up the critical inner loop.
ELI5 - Simplified Explanation
Imagine a long row of blocks, each having a different number painted on it. This code is like a game where the goal is to cut the row into small groups and make the numbers as large as possible. In each group, every number changes to match the biggest number already found in that group.
The code starts by looking at the very first block. It tries picking a group size of one block, then two blocks, and keeps going up to the size limit, which is called k. When it picks a group, it finds the biggest number inside that group and imagines all the blocks in that group becoming that big number.
While it is doing this, it remembers the groups it has already checked so it does not have to repeat the same work over and over again. This helps it find the absolute best way to slice up the whole row to get the biggest total sum. After checking all the different ways to slice the row, it knows the magic total that makes the numbers add up to the highest possible value.
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 | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| Garvit244 | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2767: Partition String Into Minimum Beautiful Substrings
Solved On The Same Day
- problem 885: Spiral Matrix III
- problem 1529: Minimum Suffix Flips
- problem 2044: Count Number of Maximum Bitwise-OR Subsets
- problem 2294: Partition Array Such That Maximum Difference Is K
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