Ninja has been given ‘N’ rectangular 3-D ‘BOXES’. Each box has dimensions Length ‘L’, Breadth ‘B’ and Height ‘H’. Ninja has to create a stack of boxes as tall as possible. But there is a condition to do so.
You can only place a box on top of another box only 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. You can rotate any box so that any side of the box is used as a base. You can take multiple instances of any box.
Can you help the Ninja to create a stack of boxes as tall as possible?.
The first line of input contains an integer ‘T’ which denotes the number of test cases or queries to be run. Then the test cases follow.
The first line of each test case contains a space-separated integer ‘N’, which represents the number of boxes.
The next ‘N’ lines of each test case contain three space-separated integers ‘L’, ‘B’, and ’H’ that represent the length, breadth, and height of a box.
Output Format :
For each test case, print the maximum height of the stack which can be made using these boxes.
Print the output of each test case in a separate line.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= ‘T’ <= 100
1 <= ‘N’ <= 5000
1 <= ‘L’, ‘B’, ‘H’ <= 100000
Time Limit: 1 second
1
3
1 2 3
2 3 4
3 4 5
15
For sample test case 1 :
In this test case, the possible rotations of all the boxes are
Box 1: 1 2 3 2 3 1 3 1 2
Box 2: 2 3 4 3 4 2 4 2 3
Box 3: 3 4 5 3 5 4 4 5 3
So we can use Box 3 with dimensions {4 5 3} as the bottom-most box.
Then we can place Box 3 with dimensions {3 4 5} on the previous box as we can use multiple instances of the same box.
Then we can place Box 2 with dimensions {2 3 4} on Box 3
Then we can place Box 1 with dimensions {1 2 3} on Box 2.
Hence the maximum height of the stack is 3 + 5 + 4 + 3 => 15
1
3
1 2 3
2 3 4
4 5 6
19
Think of the Recurrence Relation.
As we know we can place a box upon another box if the base area is smaller than the previously selected box. So, first of all, we sort the boxes according to the base area. Then we traverse through all the boxes and assume that the ‘i’th’ box is placed at the bottom. Then we try to place all the remaining boxes on this ‘i’th’ box and calculate the maximum height of the stack.
Algorithm:
ninjaAndStackOfBoxesHelper(‘BOXES’, ‘i’) function is explained below:
O(N ^ N) where ‘N’ is the number of boxes.
First, we are sorting the ‘BOXES’ array/list which takes O(N log(N) time. Then for finding the maximum height of the stack we are traversing the array/list ‘BOXES’ and for every box, we are calling our recursive function.
Hence the overall time complexity is O(N ^ N).
O(N) where ‘N’ is the number of boxes.
O(N) recursion stack is used by the recursive function. We are also using the ‘BOXES’ array/list in which we store every possible rotation of all the boxes.
So the overall space complexity is O(N).