Maximum Height by Stacking Cuboids - Problem

Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [width_i, length_i, height_i] (0-indexed).

Choose a subset of cuboids and place them on each other. You can place cuboid i on cuboid j if width_i <= width_j and length_i <= length_j and height_i <= height_j.

You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.

Return the maximum height of the stacked cuboids.

Input & Output

Example 1 — Basic Stacking
$ Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]
Output: 190
💡 Note: After sorting dimensions: [[20,45,50],[37,53,95],[12,23,45]]. Sorted cuboids: [[12,23,45],[20,45,50],[37,53,95]]. We can stack all three: 45+50+95 = 190.
Example 2 — Subset Selection
$ Input: cuboids = [[38,25,45],[76,35,3]]
Output: 76
💡 Note: After sorting: [[25,38,45],[3,35,76]]. We cannot stack them (25≤3 is false), so best is single cuboid with height 76.
Example 3 — Single Cuboid
$ Input: cuboids = [[7,11,17]]
Output: 17
💡 Note: Only one cuboid, maximum height is its largest dimension after rotation: max(7,11,17) = 17.

Constraints

  • n == cuboids.length
  • 1 ≤ n ≤ 100
  • 1 ≤ widthi, lengthi, heighti ≤ 100

Visualization

Tap to expand
Maximum Height by Stacking CuboidsInput Cuboids[50,45,20]w:50l:45h:20[95,37,53]w:95l:37h:53[45,23,12]w:45l:23h:12After Sorting & Rotation[12,23,45]height:45[20,45,50]height:50[37,53,95]height:95Optimal Stack[37,53,95]+95[20,45,50]+50[12,23,45]+45Total Height: 190Strategy: Sort dimensions, then use dynamic programmingKey insight: Smaller cuboids can stack on larger ones in all dimensions
Understanding the Visualization
1
Input
Cuboids with 3 dimensions each, can be rotated
2
Process
Sort and find optimal stacking arrangement
3
Output
Maximum achievable height of stacked cuboids
Key Takeaway
🎯 Key Insight: Sort cuboids by dimensions to transform into longest increasing subsequence problem
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~25 min Avg. Time
892 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