VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-movie-festivals/

⇱ CSES Solutions - Movie Festivals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Movie Festivals

Last Updated : 23 Jul, 2025

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:

  • Sort the movies according to their ending times.
  • Maintain a variable, say moviesWatched to store the total number of movies watched.
  • Maintain a variable, say timeElapsed to keep track of the total time elapsed while watching movies.
  • Now for each movie, check if we can watch this movie, that is starting time of the movie >= timeElapsed.
  • If we can watch the movie, then we increment the count of movies watched as well as the time elapsed.
  • If we cannot watch the movie, then we move to the next movie.
  • Return the final answer as stored in moviesWatched.

Below is the implementation of the algorithm:


Output
2

Time Complexity: O(N * logN), where N is the total number of movies.
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: