1

Ninja And Stack Of Boxes

Difficulty: HARD
Avg. time to solve
45 min
Success Rate
55%

Problem Statement
Suggest Edit

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?.

Input Format :
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.
Constraints :
1 <= ‘T’ <= 100
1 <= ‘N’ <= 5000
1 <= ‘L’, ‘B’, ‘H’ <= 100000 

Time Limit: 1 second
Sample Input 1 :
1
3
1 2 3
2 3 4
3 4 5
Sample Output 1 :
15

Explanation For Sample Output 1 :

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 
Sample Input 2 :
1
3
1 2 3
2 3 4
4 5 6
Sample Output 2 :
19
Reset Code
Full screen
copy-code
Console