Maximum Height by Stacking Cuboids Problem
Description
LeetCode Problem 1691.
Given n cuboids where the dimensions of the i^th 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.
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.
Example 2:
Input: cuboids = [[38,25,45],[76,35,3]]
Output: 76
Explanation:
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 3:
Input: cuboids = [[7,11,17],[7,17,11],[11,7,17],[11,17,7],[17,7,11],[17,11,7]]
Output: 102
Explanation:
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.length1 <= n <= 1001 <= width_i, length_i, height_i <= 100
Solution
Approach: Sorting + Dynamic Programming
Cuboid j can go on top of cuboid i when each of its three dimensions is at most the matching dimension of i.
Since cuboids can be rotated, sort the three sides of every cuboid so that length <= width <= height. If a stack is valid with any rotation, it is still valid after rotating each cuboid this way, and using the longest side as the height can only make the stack taller.
Then sort the cuboids themselves in ascending order, so a cuboid can only be placed on one that comes later.
Let f[i] be the tallest stack with cuboid i at the bottom. For each j < i whose width and height are at most those of i (its length is already at most i's because of the sort), f[i] can use f[j]:
f[i] = max(f[j]) + height[i]
The answer is the largest f[i].
Complexity: O(n^2) time and O(n) space, where n is the number of cuboids.
class Solution:
def maxHeight(self, cuboids: List[List[int]]) -> int:
for c in cuboids:
c.sort()
cuboids.sort()
n = len(cuboids)
f = [0] * n
for i in range(n):
for j in range(i):
if cuboids[j][1] <= cuboids[i][1] and cuboids[j][2] <= cuboids[i][2]:
f[i] = max(f[i], f[j])
f[i] += cuboids[i][2]
return max(f)