# Program to find maximum number of boxes we can fit inside another boxes in python

Suppose we have a list of boxes where each row represents the height and width of given boxes. We can put a box in another box if first box is smaller than the second one (when both of its width and height are smaller than the other box), we have to find the maximum number of boxes we can fit into a box.

So, if the input is like

 Width Height 12 12 10 10 6 6 5 10

then the output will be 3, as we can fit the box [6, 6] inside [10, 10] which we can be put into [12, 12] box.

To solve this, we will follow these steps −

• Define a function insert_index() . This will take arr, this_h
• l := 0
• r := size of arr - 1
• res := 0
• while l <= r, do
• m := l +(r - l) // 2
• cur_h := arr[m]
• if cur_h < this_h is non-zero, then
• res := m
• l := m + 1
• otherwise,
• r := m - 1
• return res + 1
• From the main method, do the following:
• sort the matrix based on width, if widths are same sort them based on height
• n := number of items in matrix
• heights := a list of size (n + 1) and fill it with inf
• heights[0] := -inf
• res := 0
• for each box in matrix, do
• [cur_w, cur_h] := box
• index := insert_index(heights, cur_h)
• if heights[index] >= cur_h, then
• heights[index] := cur_h
• res := maximum of res and index
• return res

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, matrix):
matrix = sorted(matrix, key=lambda x: (x[0], -x[1]))
n = len(matrix)

heights = [float("inf")] * (n + 1)
heights[0] = float("-inf")
res = 0

for box in matrix:
cur_w, cur_h = box
index = self.insert_index(heights, cur_h)

if heights[index] >= cur_h:
heights[index] = cur_h
res = max(res, index)
return res

def insert_index(self, arr, this_h):
l = 0
r = len(arr) - 1
res = 0
while l <= r:
m = l + (r - l) // 2
cur_h = arr[m]
if cur_h < this_h:
res = m
l = m + 1
else:
r = m - 1
return res + 1

ob = Solution()
matrix = [
[12, 12],
[10, 10],
[6, 6],
[5, 10]
]
print(ob.solve(matrix))

## Input

matrix = [
[12, 12],
[10, 10],
[6, 6],
[5, 10] ]

## Output

3