Box Stacking Problem

You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base. It is also allowable to use multiple instances of the same type of box. Source: http://people.csail.mit.edu/bdean/6.046/dp/. The link also has video for explanation of solution.

The Box Stacking problem is a variation of LIS problem. We need to build a maximum height stack.

Following are the key points to note in the problem statement: 1) A box can be placed on top of another box only if both width and depth of the upper placed box are smaller than width and depth of the lower box respectively. 2) We can rotate boxes such that width is smaller than depth. For example, if there is a box with dimensions {1x2x3} where 1 is height, 2×3 is base, then there can be three possibilities, {1x2x3}, {2x1x3} and {3x1x2} 3) We can use multiple instances of boxes. What it means is, we can have two different rotations of a box as part of our maximum height stack.

class Solution {
    static class box {
        int l, w, h;

        box(int l, int w, int h) {
            this.l = l;
            this.w = w;
            this.h = h;
        }
    }

    public static int maxStackHeight(box arr[], int n) {
        box[] rotated = new box[n * 3];
        int index = 0;
        for (box x : arr) {
            rotated[index++] = new box(x.l, x.w, x.h);
            rotated[index++] = new box(x.l, x.h, x.w);
            rotated[index++] = new box(x.w, x.h, x.l);
        }
        Arrays.sort(rotated, (a, b) -> b.l * b.w - a.l * a.w);
        int max = 0;
        int dp[] = new int[3 * n];
        // dp[i] -> is the max height possible upto ith index (including this box)
        dp[0] = rotated[0].h;
        for (int i = 1; i < 3 * n; i++) {
            dp[i] = rotated[i].h;
            for (int j = 0; j < i; j++) {
                if (rotated[i].l < rotated[j].l && rotated[i].w < rotated[j].w)
                    dp[i] = Math.max(dp[i], dp[j] + rotated[i].h);
            }
            max = Math.max(dp[i], max);
        }
        return max;
    }
}

Last updated