![]() |
VOOZH | about |
In a movie festival, N movies will be shown. You know the starting and ending time of each movie given as movies[][] such that movies[i][0] = starting time of ith movie and movies[i][1] = ending time of ith movie. What is the maximum number of movies you can watch entirely?
Note: If you watch a movie having ending time = T, then you can start watching any other movie whose starting time >= T.
Examples:
Input: N = 3, movies[][] = {{3, 5}, {4, 9}, {5, 8}}
Output: 2
Explanation: You can watch the first and the third movie, that is {3, 5} and {5, 8}.Input: N = 3, movies[][] = {{1, 2}, {2, 3}, {4, 5}}
Output: 3
Explanation: You can watch the first, second and third movie, that is {1, 2}, {2, 3} and {4, 5}.
Approach: To solve the problem, follow the below idea:
The problem can be solved by sorting the movies in ascending order according to the ending times. We can start from the movie with the earliest ending and watch it. Then continue moving to all the movies according to their ending times. For every subsequent movie, check if we can watch it or not. If we can watch it, then move till we find another movie whose starting time >= the current movie's ending time. After traversing through all the movies, return the final answer.
Step-by-step algorithm:
Below is the implementation of the algorithm:
2
Time Complexity: O(N * logN), where N is the total number of movies.
Auxiliary Space: O(N)