AlgoLounge

Maximum Height by Stacking Cuboids

hard

Given n cuboids where the dimensions of the i^(th) cuboid is cuboids[i] = [widthᵢ, lengthᵢ, heightᵢ] (0-indexed). Choose a subset of cuboids and place them on each other.

You can place cuboid i on cuboid j if widthᵢ <= widthⱼ and lengthᵢ <= lengthⱼ and heightᵢ <= heightⱼ. You can rearrange any cuboid's dimensions by rotating it to put it on another cuboid.

Return the maximum height of the stacked cuboids.

Example 1:

Input: cuboids = [[50,45,20],[95,37,53],[45,23,12]]
Output: 190
Explanation:
Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.
Cuboid 0 is placed next with the 45x20 side facing down with height 50.
Cuboid 2 is placed next with the 23x12 side facing down with height 45.
The total height is 95 + 50 + 45 = 190.

Examples

Example 1

Input:  cuboids = [[38,25,45],[76,35,3]]
Output: 76

You can't place any of the cuboids on the other. We choose cuboid 1 and rotate it so that the 35x3 side is facing down and its height is 76.

Example 2

Input:  cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
Output: 102

After rearranging the cuboids, you can see that all cuboids have the same dimension. You can place the 11x7 side down on all cuboids so their heights are 17. The maximum height of stacked cuboids is 6 * 17 = 102.

Constraints

  • n == cuboids.length
  • 1 <= n <= 100
  • 1 <= widthᵢ, lengthᵢ, heightᵢ <= 100
TypeScript
Loading editor…
List of test cases (12)
Case 1
cuboids = [[50,45,20],[95,37,53],[45,23,12]]
Case 2
cuboids = [[38,25,45],[76,35,3]]
Case 3
cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
Case 4
cuboids = [[1,1,1]]
Case 5
cuboids = [[100,100,100]]
Case 6
cuboids = [[1,2,3],[4,5,6],[7,8,9]]
Case 7
cuboids = [[10,20,30],[10,20,30],[10,20,30]]
Case 8
cuboids = [[5,5,5],[4,4,4],[3,3,3],[2,2,2],[1,1,1]]
Case 9
cuboids = [[100,1,1],[1,100,1],[1,1,100]]
Case 10
cuboids = [[2,3,5],[3,5,2],[5,2,3]]
Case 11
cuboids = [[50,50,50],[40,45,60],[30,40,55]]
Case 12
cuboids = [[10,10,10],[20,20,20],[30,30,30],[40,40,40]]