VOOZH about

URL: https://www.geeksforgeeks.org/dsa/activity-selection-problem-greedy-algo-1/

⇱ Activity Selection - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Activity Selection

Last Updated : 8 Sep, 2025

Given two arrays start[] and finish[], representing the start and finish times of activities. A person can perform only one activity at a time, and an activity can be performed only if its start time is greater than the finish time of the last chosen activity.
Find the maximum number of activities that can be performed without overlapping.

Examples:  

Input: start[] = [1, 3, 0, 5, 8, 5], finish[] = [2, 4, 6, 7, 9, 9]
Output: 4
Explanation: A person can perform at most four activities. The maximum set of activities that can be performed is {0, 1, 3, 4} (these are the indexes in the start[] and finish[] arrays).

Input: start[] = [10, 12, 20], finish[] = [20, 25, 30]
Output: 1
Explanation: A person can perform at most one activity.

[Naive Approach] Generate All Subsets - O(2n) Time and O(n) Space

Generates all possible subsets of activities, where each subset represents a potential selection. For each subset, we check if the activities are mutually non-overlapping by comparing their time intervals pairwise. If a subset is valid and contains more activities than our current maximum, we update the maximum count. In the end, we get the size of the largest valid subset.

Note: Generating all possible subsets and checks them one by one will lead to an exponential time complexity, which becomes impossible to compute for larger values of n. Hence, this approach is not practical.

[Expected Approach 1] - Using Sorting - O(n * log(n)) Time and O(n) Space

The problem can be solved using a greedy approach. The idea is that whenever multiple activities overlap, we should pick the one that finishes earliest, because finishing sooner leaves the most room to schedule upcoming activities. This way, the schedule stays flexible, and more activities can fit without conflict.

To achieve this, we sort all activities by their finishing times. Then, starting with the first one, we repeatedly pick the next activity that both starts after the last selected activity ends and has the earliest finish time among the remaining ones.



Output
4

[Expected Approach 2] - Using Priority Queue - O(n * log(n)) Time and O(n) Space

Instead of sorting, we can also use a min-heap (priority queue) to directly process activities in order of their finishing time. By storing each activity as (finish, start) in the heap, the activity with the earliest finish time is always available at the top. We then apply the same greedy rule as above: pick it if its start time is after the last chosen activity’s finish, update the finish time, and continue.


Output
4
Comment