Python 1691.py
class Solution:
def maxHeight(self, cuboids: List[List[int]]) -> int:
# rotate each cuboid such that width <= length <= height
for c in cuboids:
c.sort()
# sort all cuboids by their width (and length/height if same width)
cuboids.sort()
@cache
def deeper(i): # stack cuboids from 0 to i, return their height
result = 0
current = cuboids[i]
for j in range(i):
other = cuboids[j]
if other[1] <= current[1] and other[2] <= current[2]: # always other[0] <= current[0]
# stack both
result = max(result, deeper(j))
# add current cuboid's height, too
return result + current[2]
return max([ deeper(i) for i in range(len(cuboids)) ])
Difficulty
and has an acceptance rate of about 62% (70k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Sorting
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 stacking a set of rectangular cuboids to achieve the greatest possible total height. Each cuboid may be rotated arbitrarily before stacking, and a cuboid can be placed on top of another only when its three dimensions are each less than or equal to the corresponding dimensions of the cuboid beneath it. The algorithm first normalizes the orientation of every cuboid, orders the entire collection to simplify comparison, and then employs a memoized depth-first search to explore all feasible stacking sequences, finally returning the maximum attainable height.
Normalizing Cuboid Orientation
The first logical block ensures that every cuboid is represented in a canonical orientation where the three side lengths are ordered from smallest to largest. By sorting the inner list of each cuboid, the code guarantees that the first element is the smallest dimension (treated as width), the second is the middle dimension (treated as length), and the third is the largest dimension (treated as height). This eliminates the need to consider the six possible rotations of a cuboid during the stacking phase.
for c in cuboids:
c.sort()
Because the dimensions are sorted in-place, subsequent comparisons can rely on a consistent ordering without additional transformation logic.
Global Ordering of Cuboids
After each cuboid has been normalized, the entire list of cuboids is sorted lexicographically. The primary key of this sort is the smallest dimension (width); ties are resolved automatically by the second and third dimensions (length and height). This global ordering creates a sequence where any cuboid that appears later in the list has a width that is at least as large as the width of any earlier cuboid. Consequently, when the algorithm examines potential predecessors for a given cuboid, the width condition is implicitly satisfied, and only the length and height need explicit checks.
cuboids.sort()
The sorted order also enables the dynamic programming step to consider only earlier indices as possible bases, which reduces the search space dramatically.
Memoized Depth-First Search
The core of the solution is a recursive function deeper(i) that computes the maximum stack height achievable when the cuboid at index i is placed at the top of the stack. The function is decorated with @cache, which stores the result for each index after the first computation. This memoization prevents repeated evaluation of identical subproblems, turning an exponential exploration into a polynomial-time process.
@cache
def deeper(i):
result = 0
current = cuboids[i]
for j in range(i):
other = cuboids[j]
if other[1] <= current[1] and other[2] <= current[2]:
result = max(result, deeper(j))
return result + current[2]
Inside the loop, the algorithm checks whether the length (other[1]) and height (other[2]) of a candidate lower cuboid are not greater than those of the current cuboid. The width condition (other[0] <= current[0]) is guaranteed by the earlier global sort, so it is omitted from the explicit test. When a valid predecessor is found, the function recursively obtains the best height achievable with that predecessor at the top, and updates result with the maximum of all such possibilities. After the loop, the height of the current cuboid (current[2]) is added, yielding the total height for a stack ending with this cuboid.
Determining the Overall Maximum
The final step evaluates deeper(i) for every cuboid index and selects the greatest value. Because each call to deeper already incorporates the optimal height of any stack that ends with the corresponding cuboid, the outer max yields the height of the tallest possible stack across all configurations.
return max([ deeper(i) for i in range(len(cuboids)) ])
The list comprehension generates the height for each possible top cuboid, and the built-in max extracts the maximum.
Edge Cases Handled
The algorithm gracefully manages situations where multiple cuboids share identical dimensions. Since the comparison uses <= for length and height, cuboids with equal side lengths can be stacked in any order without violating the stacking rule. The initial sorting of each cuboid also ensures that degenerate cuboids (for example, those with two or three equal dimensions) are treated consistently.
When the input contains a single cuboid, the recursion never enters the inner loop, result remains zero, and the function returns the height of that solitary cuboid, which is correctly identified as the maximum stack height.
If the collection includes cuboids whose smallest dimension is zero, the sorting and comparison logic still functions because zero is a valid numeric value; the width condition is satisfied automatically by the global ordering, and the length/height checks handle the zero case without special treatment.
Performance Optimizations
The most significant optimization is the use of memoization via @cache. By storing the result of deeper(i) after its first computation, the algorithm avoids recomputing the same sub-stack heights for different branches of the recursion tree. This transforms the naive exponential recursion into a dynamic programming solution whose runtime grows roughly with the square of the number of cuboids.
Sorting each cuboid individually reduces the rotational search space from six possibilities per cuboid to a single canonical orientation, eliminating combinatorial explosion at the earliest stage. The subsequent global sort imposes a partial order that eliminates the need to check the width dimension during the inner loop, cutting down the number of comparisons per iteration.
The final max over a list comprehension leverages Python’s highly optimized built-in functions, ensuring that the aggregation of results is performed efficiently without explicit loops.
Overall, the combination of canonical orientation, global ordering, and memoized recursion yields a solution that explores the necessary stacking configurations while keeping redundant work to a minimum.
ELI5 - Simplified Explanation
Imagine you have a giant box filled with wooden blocks of many different sizes. Each block is like a little building, and the goal is to see how tall a tower you can build.
To make the tower sturdy, you have to follow a special rule. You can turn each block around so that the smallest side is on the bottom and the biggest side is pointing up toward the sky. Once every block is positioned this way, it is time to line them up in a neat row.
Now, think about building the tower one block at a time. To put a block on top of another one, you must make sure the block underneath is bigger in every way than the one you are adding. If the block on the bottom is wide enough and long enough to hold the new one, you can stack them safely.
The code looks at every single block and asks if it can sit on top of any of the other blocks that came before it in the line. By checking all the possibilities, it finds the tallest possible tower you can build without the blocks tumbling over. It tries every combination until it discovers which group of blocks stacked together creates the most impressive height.
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++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | JS | Java | Go | Python | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1996: The Number of Weak Characters in the Game
- problem 2358: Maximum Number of Groups Entering a Competition
Solved On The Same Day
- problem 1694: Reformat Phone Number
- problem 1664: Ways to Make a Fair Array
- problem 1575: Count All Possible Routes
- problem 1665: Minimum Initial Energy to Finish Tasks
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