Suppose we have a list of intervals for different movie showings (they can be overlapped), we have to find the minimum number of theatres required to be able to show all of the movies.
So, if the input is like intervals = [[20, 65],[0, 40],[50, 140]], then the output will be 2, as [20, 65] and [0, 40] are overlapping. [20, 65] and [50, 140] are also overlapping but [0, 40] and [50, 140] are not. So we need 2 theaters.
To solve this, we will follow these steps:
- t := a new list
- for each interval [a, b] in intervals, do
- insert [a, 1] at the end of t
- insert [b, -1] at the end of t
- ans := 0, count := 0
- for each pair (x, d) in t in sorted form, do
- count := count + d
- ans := maximum of ans and count
- return ans
Let us see the following implementation to get better understanding:
Example Code
class Solution: def solve(self, intervals): t = [] for a, b in intervals: t.append((a, 1)) t.append((b, -1)) ans = count = 0 for x, d in sorted(t): count += d ans = max(ans, count) return ans ob = Solution() intervals = [[20, 65],[0, 40],[50, 140]] print(ob.solve(intervals))
Input
[[20, 65],[0, 40],[50, 140]]
Output
2