Description
Given a list of time exclusive intervals
for different movie showings (possibly overlapping), find the minimum number of theaters required to be able to show all movies.
Constraints:
- •
0 ≤ n ≤ 100,000
wheren
is the length ofintervals
Example 1
Input
intervals = [
[30, 75],
[0, 50],
[60, 150]
]
Output
2
Explanation
[30, 75] and [0, 50] overlap. [30, 75] and [60, 150] also overlap but later on. So the max number here is 2.
Example 2
Input
intervals = [
[10, 20],
[20, 30]
]
Output
1
Explanation
Boundaries are exclusive so these intervals are not considered overlapping.
Example 3
Input
intervals = [
[0, 1],
[0, 1],
[0, 1]
]
Output
3
Explanation
The three intervals happen all at the same time so we need 3.
Intuition
- sort intervals by start time increasing order
- create a priority_queue to store end times by increasing order
- compare start time and the top end time in priority queue
- if start time is earlier than top end time, so we need one more theater
- else just pop this movie out of priority queue
Implementation
int solve(vector<vector<int>>& intervals) {
int n = intervals.size();
if (n <= 1) return n;
sort(intervals.begin(), intervals.end());
priority_queue<int, vector<int>, greater<int>> endTimes;
endTimes.push(intervals[0][1]);
int cnt = 1;
for (int i = 1; i < intervals.size(); i++) {
int startTime = intervals[i][0], endTime = intervals[i][1];
if (startTime < endTimes.top())
cnt++;
else
endTimes.pop();
endTimes.push(endTime);
}
return cnt;
}
Time Complexity
- Time: O(nlogn)
- Space: O(n)
Top comments (0)