Skip to content

08.13. Pile Box

Description

You have a stack of n boxes, with widths wi, heights hi, and depths di. The boxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height, and depth. Implement a method to compute the height of the tallest possible stack. The height of a stack is the sum of the heights of each box.

The input use [wi, di, hi] to represents each box.

Example1:


 Input: box = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]

 Output: 6

Example2:


 Input: box = [[1, 1, 1], [2, 3, 4], [2, 6, 7], [3, 4, 5]]

 Output: 10

Note:

  1. box.length <= 3000

Solutions

Solution 1: Sorting + Dynamic Programming

First, we sort the boxes in ascending order by width and descending order by depth, then use dynamic programming to solve the problem.

We define $f[i]$ as the maximum height with the $i$-th box at the bottom. For $f[i]$, we enumerate $j \in [0, i)$, if $box[j][1] < box[i][1]$ and $box[j][2] < box[i][2]$, then we can put the $j$-th box on top of the $i$-th box, in which case $f[i] = \max{f[i], f[j]}$. Finally, we add the height of the $i$-th box to $f[i]$ to get the final value of $f[i]$.

The answer is the maximum value in $f$.

The time complexity is $O(n^2)$, and the space complexity is $O(n)$. Here, $n$ is the number of boxes.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def pileBox(self, box: List[List[int]]) -> int:
        box.sort(key=lambda x: (x[0], -x[1]))
        n = len(box)
        f = [0