The Box Stacking problem is a classic dynamic programming problem where given a set of boxes, the task is to find the maximum height that can be obtained by stacking the boxes on top of each other with the constraint that a box can only be placed on top of another box if its width and depth are smaller than the box below it.
We can solve this problem using dynamic programming in the following steps:
Step 1: Create an array of all possible rotations for each box. For example, if a box has dimensions (l, w, h), then all possible rotations can be (w,h,l), (h,l,w), (l,w,h).
Step 2: Sort the array of all boxes in descending order of the base area (width times depth).
Step 3: Create a new array dp[] where dp[i] stores the maximum height that can be achieved by using the ith box at the bottom of the stack. Initialize dp[] with the heights of each box.
Step 4: For each box i, check if it can be placed on top of another box j. If yes, then update dp[i] as dp[j] + height[i]. Also, keep track of the maximum height achieved so far.
Step 5: Return the maximum height achieved from dp[] array.
The Java implementation of the above steps is as follows:
class Box implements Comparable<Box>{
int l, w, h, area;
Box(int l, int w, int h) {
this.l = l;
this.w = w;
this.h = h;
area = l*w;
}
public int compareTo(Box b) {
return b.area - this.area;
}
}
class BoxStacking {
public int maxHeight(Box[] boxes) {
int n = boxes.length;
Box[] allBoxes = new Box[3*n];
int index = 0;
for(int i=0; i<n; i++) {
Box box = boxes[i];
allBoxes[index++] = new Box(box.l, box.w, box.h);
allBoxes[index++] = new Box(box.w, box.h, box.l);
allBoxes[index++] = new Box(box.h, box.l, box.w);
}
Arrays.sort(allBoxes);
int[] dp = new int[3*n];
for(int i=0; i<3*n; i++) {
dp[i] = allBoxes[i].h;
}
int maxHeight = 0;
for(int i=1; i<3*n; i++) {
for(int j=0; j<i; j++) {
if(allBoxes[i].l < allBoxes[j].l && allBoxes[i].w < allBoxes[j].w) {
dp[i] = Math.max(dp[i], allBoxes[i].h + dp[j]);
}
}
maxHeight = Math.max(maxHeight, dp[i]);
}
return maxHeight;
}
}
In the above implementation, the Box class represents each box with its dimensions and the compareTo method is used to sort the boxes in descending order of the base area. The maxHeight method takes an array of all boxes as input and returns the maximum height achieved.
We first create an array of all possible rotations for each box and sort them in descending order of the base area. We then initialize the dp[] array with the heights of each box.
We then iterate through each box i and check if it can be placed on top of another box j. If yes, then we update dp[i] as dp[j] + height[i]. We also keep track of the maximum height achieved so far. Finally, we return the maximum height from dp[] array.
The time complexity of the above implementation is O(n2) and the space complexity is O(n).