Problem Description
Given n cuboids where the i-th cuboid has dimensions cuboids[i] = [width, length, height], you can reorder the dimensions of each cuboid. Choose a subset of cuboids and stack them one on top of another such that for any cuboid placed on top of another, its dimensions are less than or equal to the ones below it. Return the maximum possible total height of the stacked cuboids.
Key Insights
- Each cuboid’s dimensions can be rearranged. Sort the dimensions of each cuboid so that comparisons become straightforward.
- Sort the list of cuboids (after internal sorting) by their dimensions to enforce an order that makes stacking validation efficient.
- Use dynamic programming (DP) to build up the answer by checking, for every cuboid, which previous cuboids can support it.
- The stacking condition is checked coordinate-wise since after sorting dimensions, the smallest two act as base dimensions and the largest as height.
- The problem resembles the Longest Increasing Subsequence (LIS) type, but with a three-dimensional twist.
Space and Time Complexity
Time Complexity: O(n^2) where n is the number of cuboids (plus an O(n log n) sorting overhead, which is dominated by O(n^2) for n up to 100). Space Complexity: O(n) for the DP array.
Solution
The solution starts by sorting the dimensions of each cuboid so that the smallest dimension comes first and the largest (which will always be the height when placed optimally) comes last. After that, we sort the list of cuboids by their dimensions. We then use dynamic programming, where dp[i] represents the maximum stack height ending with the i-th cuboid in the sorted order. For each cuboid i, we check all previous cuboids j. If cuboid i can be stacked on top of cuboid j (i.e., every dimension of i is greater than or equal to the corresponding dimension of j), then we update dp[i] accordingly. Finally, the maximum value in our dp array is the answer.