Maximum Height by Stacking Cuboids - Problem
Cuboid Tower Challenge

Imagine you have a collection of n cuboids (3D rectangular boxes), each with dimensions [width, length, height]. Your goal is to build the tallest possible tower by stacking some or all of these cuboids on top of each other.

The Rules:
• You can rotate any cuboid to rearrange its dimensions before stacking
• Cuboid A can be placed on cuboid B only if all dimensions of A are ≤ the corresponding dimensions of B
• You want to maximize the total height of your tower

Input: Array of cuboids where cuboids[i] = [width_i, length_i, height_i]
Output: Maximum possible height of the stacked tower

This is a classic 3D extension of the box stacking problem that combines dynamic programming with clever sorting strategies.

Input & Output

example_1.py — Basic Stacking
$ Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]
Output: 190
💡 Note: One optimal stacking: Cuboid 1 rotated to [50,45,20], Cuboid 2 rotated to [95,53,37], and Cuboid 3 rotated to [95,23,12]. Total height = 20 + 37 + 12 = 69. Actually, better rotation gives us [95,37,53] + [50,45,20] + [45,23,12] = 53 + 20 + 12 = 85. The optimal is 190 when using all dimensions optimally.
example_2.py — No Valid Stacking
$ Input: cuboids = [[38,25,45],[76,35,3]]
Output: 76
💡 Note: Cannot stack these cuboids due to dimension constraints. The best we can do is use the single cuboid with maximum dimension, which is 76.
example_3.py — Single Cuboid
$ Input: cuboids = [[7,11,17]]
Output: 17
💡 Note: Only one cuboid available. The maximum dimension is 17, so that's our answer.

Constraints

  • n == cuboids.length
  • 1 ≤ n ≤ 100
  • 1 ≤ widthi, lengthi, heighti ≤ 100
  • All dimensions are positive integers

Visualization

Tap to expand
100×60×4060×50×3030×20×25Optimal TowerHeight: 40+30+25 = 95DP Algorithm1. Generate rotations: 6n cuboids2. Sort by dimensions: O(n log n)3. DP: dp[i] = max height ending at i4. For each pair (i,j): check stacking5. Update: dp[i] = max(dp[i], dp[j] + h[i])Time: O(n² log n)
Understanding the Visualization
1
Rotate & Sort
Generate all 6 rotations for each cuboid and sort dimensions
2
Dynamic Programming
For each position, find the best foundation from previous cuboids
3
Build Tower
Stack cuboids following the constraint that each upper cuboid fits within the lower one
Key Takeaway
🎯 Key Insight: Sort all rotations by dimensions, then use DP to find optimal stacking order
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
25.7K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen