Program to find number of boxes that form longest chain in Python?


Suppose we have a list of boxes, here each entry has two values [start, end] (start < end). We can join two boxes if the end of one is equal to the start of another. We have to find the length of the longest chain of boxes.

So, if the input is like blocks = [ [4, 5], [5, 6], [4, 8], [1, 2], [2, 4] ], then the output will be 4, as we can form the chain: [1, 2], [2, 4], [4, 5], [5, 6]

To solve this, we will follow these steps:

  • if boxes are empty, then

    • return 0

  • sort the list boxes

  • dic := an empty map

  • for each start s and end e in boxes, do

    • dic[e] := maximum of dic[e] and dic[s] + 1

  • return maximum of the list of all values of dic

Let us see the following implementation to get better understanding:

Example

 Live Demo

import collections

class Solution:
   def solve(self, boxes):
      if not boxes:
         return 0
      boxes.sort()
      dic = collections.defaultdict(int)
      for s, e in boxes:
         dic[e] = max(dic[e], dic[s] + 1)
      return max(dic.values())

ob = Solution()
boxes = [
   [4, 5],
   [5, 6],
   [4, 8],
   [1, 2],
   [2, 4]
]
print(ob.solve(boxes))

Input

[[4, 5],
[5, 6],
[4, 8],
[1, 2],
[2, 4] ]

Output

4

Updated on: 10-Nov-2020

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements