- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements