Box Stacking Problem - Problem

You are given a set of n rectangular boxes, each with width, height, and depth dimensions. Your goal is to stack these boxes to create the tallest possible tower.

Stacking Rules:

  • A box can be placed on top of another box only if both its width and depth are strictly smaller than the box below it
  • You can use any number of instances of each box type
  • Each box can be rotated to create different orientations (width×height×depth, height×width×depth, depth×width×height)

Return the maximum height of the tallest possible tower you can build.

Example: If you have boxes [(4,6,7), (1,2,3), (4,5,6)], you can rotate them to create orientations like (4,6,7), (6,4,7), (7,4,6), etc., then stack them optimally.

Input & Output

Example 1 — Basic Box Stacking
$ Input: boxes = [[4,6,7],[1,2,3],[4,5,6]]
Output: 18
💡 Note: Optimal stacking: (7×4×6) base with height 6, then (6×4×7) with height 4, then (4×5×6) with height 5, then (3×1×2) with height 2. Total height: 6+4+5+2 = 17. But better: (7×4×6) base height 6 + (5×4×6) height 5 + (3×1×2) height 2 + another orientation gives 18.
Example 2 — Single Box
$ Input: boxes = [[1,2,3]]
Output: 3
💡 Note: Only one box, so we use its tallest orientation: 3×1×2 with height 3, or 2×3×1 with height 1, or 1×2×3 with height 2. Maximum is 3.
Example 3 — No Valid Stacking
$ Input: boxes = [[5,5,5],[5,5,5]]
Output: 5
💡 Note: Both boxes have identical dimensions, so they cannot be stacked (need strictly smaller dimensions). Best we can do is use one box with height 5.

Constraints

  • 1 ≤ boxes.length ≤ 100
  • 1 ≤ width, height, depth ≤ 100
  • All dimensions are positive integers

Visualization

Tap to expand
INPUTALGORITHMRESULT4×6×71×2×34×5×6Original BoxesNeed to stack optimallyConstraint: width < base_widthand depth < base_depth1Generate OrientationsCreate all rotations of each box2Sort by Base AreaLargest base areas first3Dynamic ProgrammingBuild optimal tower height4Return MaximumBest tower height foundHEIGHT18Optimal Tower Stack:7×4×6 (height 6)6×4×5 (height 5)4×3×5 (height 4)3×1×2 (height 2)1×1×2 (height 1)Total: 6+5+4+2+1 = 18Key Insight:Sort all box orientations by base area, then use DP where each box builds on the tallest valid foundation from larger bases!TutorialsPoint - Box Stacking Problem | Dynamic Programming Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~35 min Avg. Time
890 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