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
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 −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, matrix): matrix = sorted(matrix, key=lambda x: (x, -x)) n = len(matrix) heights = [float("inf")] * (n + 1) heights = 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))
matrix = [ [12, 12], [10, 10], [6, 6], [5, 10] ]