Box Stacking Problem
You are given three integer arrays of size N, which represent the height, width and length of N boxes, respectively.
Your task is to stack the boxes on each other such that the height should be maximum, and you have to return the height.
To put one box on top of another box, the dimension of the top box should be strictly less than the dimension of the bottom box, which means the length and width of the top boxes should be strictly smaller than the bottom box.
We can have multiple instances of a box, which means we can rotate the box as we want and then use it as another box. We know there are six faces of a cuboid. We can have six instances of a box, but there will be only three unique instances, so indirectly, we will have 3*N boxes with different dimensions, and we have to find the maximum height.
We will use a dynamic programming approach here to solve this problem. We will sort the array based on its width, and then we will try to find out the longest Increasing Subsequence (LIS) to get the maximum height.
In the above code, we are given three different arrays representing the height, width and length of four different boxes. As we know, we can rotate the box to create its instance, so indirectly, we will have 12 options or 12 boxes for this problem.
We will create the pair class to store the dimensions and write the comparator for our ArrayList. We will iterate over the array, and we will check three cases for each box to get its three instances.
Case 1: If the width of the box is smaller than the length, then we will add as dimension as it is. Otherwise, we will swap width with length and add it as a new box.
Case2: If the height of the box is smaller than the length, then we will swap the height and width; otherwise, we will swap the width with height and again height with length and add it as a new box.
Case3: If the height of the box is smaller than the width, then we will swap width and length and then length and height to get the new dimension box. Otherwise, we will swap height with length and add it as a new box.
After adding all the relevant boxes to ArrayList, we will sort them in ascending order according to their widths.
We will use the LIS (Longest Increasing Subsequence) technique to get the solution. We will create the dp array of size the same as ArrayList.
dp[i] will store the maximum height we can get by stacking the box from 0 to i-1 if the base of the stack is the ith box.
If it is the first box, then the maximum height will be its height so that it will be a base case.
Now for the rest of the boxes, we will loop from 0 to i-1 and get the maximum value of dp[j], and we will add the maximum value and height of the ith box to get the maximum size of the box.
The maximum value of the dp array will be our answer.
In the above example, we have four boxes so we will create its 12 instances as follows:
Time complexity: O(N2)
Space complexity: O(N)
Next TopicK Most Frequent Elements in Java