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 Cuboids INPUT 3 Cuboids (can rotate) [50,45,20] Cuboid 0 [95,37,53] Cuboid 1 [45,23,12] Cuboid 2 Input Array: cuboids = [[50,45,20], [95,37,53],[45,23,12]] Dimensions can be rotated to maximize height ALGORITHM (DP) 1 Sort Each Cuboid Arrange dims: w <= l <= h [20,45,50],[37,53,95],[12,23,45] 2 Sort All Cuboids By dimensions ascending [12,23,45],[20,45,50],[37,53,95] 3 DP: Stack Check For each i, check all j < i if j can be placed on i DP Table (dp[i] = max height ending at i) dp[0] = 45 dp[1] = 45 + 50 = 95 dp[2] = 95 + 95 = 190 4 Return Max max(dp) = 190 FINAL RESULT Optimal Stack (bottom to top) [37,53,95] h = 95 [20,45,50] h = 50 [12,23,45] h = 45 Total Output: 190 45 + 50 + 95 = 190 Key Insight: Sort each cuboid's dimensions so height is largest, then sort all cuboids. Use LIS-style DP: dp[i] = max height of stack ending with cuboid i. Cuboid j can stack on i if all dimensions of j are <= corresponding dimensions of i. TutorialsPoint - Maximum Height by Stacking Cuboids | DP Approach
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