Activity Selection Problem
Given activities with start and finish times, choose the largest set that never overlap. Always taking the one that finishes first is provably optimal.
One Room, Many Requests
- Input – n activities with start times s₁…sₙ and finish times f₁…fₙ.
- Constraint – chosen activities must be pairwise compatible: sⱼ ≥ fᵢ or sᵢ ≥ fⱼ.
- Goal – maximise the number of activities chosen, not the time used.
The problem gives n activities, each with a start time sᵢ and a finish time fᵢ, competing for one resource such as a room, a machine or a lecture hall. Only one activity can use the resource at a time. The task is to select the maximum number of mutually compatible activities.
Two activities are compatible when their intervals do not overlap: one finishes at or before the moment the other starts. Treating each activity as the half-open interval [sᵢ, fᵢ) makes back-to-back activities, where one ends at 5 and the next starts at 5, compatible.
It is the textbook example of a greedy algorithm because a simple local rule, applied once per activity, produces a globally optimal answer, and the proof of that is short enough to reproduce in an exam.
- Also called the interval scheduling problem
- Maximise the count of activities, not the hours of room use
The Greedy Choice: Earliest Finish Time
Several greedy rules sound plausible. Only one of them works. The right question is: which first activity leaves the most room for the rest? The answer is the one that finishes earliest, because every other activity would leave the resource busy for at least as long.
The other rules fail on tiny inputs. Earliest start can pick a long activity that blocks everything. Shortest duration can pick a short activity that straddles two others. Fewest overlaps fails on a more contrived case. Earliest finish never fails, and the section on the proof explains why.
| Rule | Counterexample | Rule picks | Optimal |
|---|---|---|---|
| Earliest start | [0,10), [1,3), [4,6) | 1 activity | 2 |
| Shortest duration | [0,5), [4,6), [5,10) | 1 activity | 2 |
| Fewest conflicts | a symmetric 11-interval layout | 3 activities | 4 |
| Earliest finish | none exists | optimal | optimal |
- One counterexample is enough to reject a greedy rule; proving one right takes an argument
The Algorithm: Sort, Then One Scan
- Sort the activities in increasing order of finish time.
- Take the first activity and set
lastFinishto its finish time. - Scan the remaining activities in order: if
start ≥ lastFinish, take it and setlastFinish = finish. - Skip any activity with
start < lastFinish; it overlaps a chosen one. - Return the chosen set; its size is the maximum.
The activity selection algorithm sorts the activities by finish time and takes the first one. Then scan the rest in order and take each activity whose start time is at least the finish time of the last activity taken.
The scan compares every activity with a single number, the last finish time, because the sorted order guarantees the most recently chosen activity is the one that ends latest. Sorting dominates, so the algorithm runs in O(n log n) time. If the input already arrives sorted by finish time, it is O(n). Extra space is O(1) beyond the output.
- Use ≥, not >, when an activity may start exactly as another ends
- Ties in finish time can be broken either way; the count does not change
- Empty input gives an empty set; any non-empty input takes at least one activity
Terms, operations, and practical uses
Core vocabulary
- CompatibleTwo activities whose intervals do not overlap; one finishes at or before the other starts.
- Greedy-choice propertySome optimal solution contains the locally best choice.
- Optimal substructureAfter the first choice, the rest is a smaller copy of the problem.
- Exchange argumentSwap an element of an optimal solution for the greedy choice without losing optimality.
Costs
- Sort by finishO(n log n), the dominant cost.
- Greedy scanO(n): one comparison per activity.
- Pre-sorted inputO(n) total.
- Weighted versionO(n log n) with DP and binary search.
Related lessons and problems
- Greedy AlgorithmsWhen a local choice is safe, and how to prove it.
- Dynamic ProgrammingThe tool for the weighted version.
- N Meetings in One RoomActivity selection as a coding problem.
- Non-overlapping IntervalsThe same greedy, counting removals instead.
Code in Python, C++ and Java
def select_activities(activities):
# Sort by finish time; ties do not matter for the count.
ordered = sorted(activities, key=lambda a: a[2])
chosen = []
last_finish = float("-inf")
for name, start, finish in ordered:
if start >= last_finish: # compatible with everything chosen so far
chosen.append((name, start, finish))
last_finish = finish
return chosen
activities = [
("a10", 2, 14), ("a3", 0, 6), ("a7", 6, 10), ("a1", 1, 4),
("a11", 12, 16), ("a5", 3, 9), ("a8", 8, 11), ("a2", 3, 5),
("a9", 8, 12), ("a4", 5, 7), ("a6", 5, 9),
]
chosen = select_activities(activities)
for name, start, finish in chosen:
print(f"{name}: [{start}, {finish})")
print("Maximum number of activities:", len(chosen))
# The two rules that look reasonable but are not optimal.
print("Earliest finish on b:", len(select_activities([("b1", 0, 10), ("b2", 1, 3), ("b3", 4, 6)])))
print("Earliest finish on c:", len(select_activities([("c1", 0, 5), ("c2", 4, 6), ("c3", 5, 10)])))#include <algorithm>
#include <iostream>
#include <limits>
#include <string>
#include <vector>
struct Activity {
std::string name;
int start, finish;
};
std::vector<Activity> selectActivities(std::vector<Activity> activities) {
// Sort by finish time; ties do not matter for the count.
std::sort(activities.begin(), activities.end(),
[](const Activity& a, const Activity& b) { return a.finish < b.finish; });
std::vector<Activity> chosen;
int lastFinish = std::numeric_limits<int>::min();
for (const Activity& a : activities) {
if (a.start >= lastFinish) { // compatible with everything chosen so far
chosen.push_back(a);
lastFinish = a.finish;
}
}
return chosen;
}
int main() {
std::vector<Activity> activities = {
{"a10", 2, 14}, {"a3", 0, 6}, {"a7", 6, 10}, {"a1", 1, 4},
{"a11", 12, 16}, {"a5", 3, 9}, {"a8", 8, 11}, {"a2", 3, 5},
{"a9", 8, 12}, {"a4", 5, 7}, {"a6", 5, 9},
};
std::vector<Activity> chosen = selectActivities(activities);
for (const Activity& a : chosen) {
std::cout << a.name << ": [" << a.start << ", " << a.finish << ")\n";
}
std::cout << "Maximum number of activities: " << chosen.size() << '\n';
// The two rules that look reasonable but are not optimal.
std::cout << "Earliest finish on b: "
<< selectActivities({{"b1", 0, 10}, {"b2", 1, 3}, {"b3", 4, 6}}).size() << '\n';
std::cout << "Earliest finish on c: "
<< selectActivities({{"c1", 0, 5}, {"c2", 4, 6}, {"c3", 5, 10}}).size() << '\n';
}import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
record Activity(String name, int start, int finish) {}
static List<Activity> selectActivities(List<Activity> activities) {
// Sort by finish time; ties do not matter for the count.
List<Activity> ordered = new ArrayList<>(activities);
ordered.sort(Comparator.comparingInt(Activity::finish));
List<Activity> chosen = new ArrayList<>();
int lastFinish = Integer.MIN_VALUE;
for (Activity a : ordered) {
if (a.start() >= lastFinish) { // compatible with everything chosen so far
chosen.add(a);
lastFinish = a.finish();
}
}
return chosen;
}
public static void main(String[] args) {
List<Activity> activities = List.of(
new Activity("a10", 2, 14), new Activity("a3", 0, 6), new Activity("a7", 6, 10),
new Activity("a1", 1, 4), new Activity("a11", 12, 16), new Activity("a5", 3, 9),
new Activity("a8", 8, 11), new Activity("a2", 3, 5), new Activity("a9", 8, 12),
new Activity("a4", 5, 7), new Activity("a6", 5, 9));
List<Activity> chosen = selectActivities(activities);
for (Activity a : chosen) {
System.out.println(a.name() + ": [" + a.start() + ", " + a.finish() + ")");
}
System.out.println("Maximum number of activities: " + chosen.size());
// The two rules that look reasonable but are not optimal.
System.out.println("Earliest finish on b: " + selectActivities(List.of(
new Activity("b1", 0, 10), new Activity("b2", 1, 3), new Activity("b3", 4, 6))).size());
System.out.println("Earliest finish on c: " + selectActivities(List.of(
new Activity("c1", 0, 5), new Activity("c2", 4, 6), new Activity("c3", 5, 10))).size());
}
}Step through it
Running on a1..a11 with (start, finish): (1,4) (3,5) (0,6) (5,7) (3,9) (5,9) (6,10) (8,11) (8,12) (2,14) (12,16)
Proof That the Greedy Choice Is Optimal
- Let g₁ be the activity with the earliest finish time, and O = {o₁, o₂, …, oₖ} an optimal set sorted by finish time.
- Exchange – form O′ = O − {o₁} ∪ {g₁}.
- Feasible – f(g₁) ≤ f(o₁) ≤ s(o₂), so g₁ overlaps nothing in O′.
- Optimal – |O′| = |O| = k, so O′ is optimal and contains g₁.
- Induct – the rest of O′ is optimal for activities starting after f(g₁), the same problem, smaller.
The proof has two parts, the pattern used for every greedy algorithm: the greedy-choice property (some optimal solution contains the greedy choice) and optimal substructure (what remains after that choice is a smaller instance of the same problem).
The diagram at the top of the page is the first part. Let g₁ be the activity that finishes first and let O be any optimal set, with first activity o₁. Since f(g₁) ≤ f(o₁), replacing o₁ with g₁ cannot create an overlap with o₂, which starts after o₁ finished. The new set is the same size, so it is also optimal, and it contains g₁.
For the second part, once g₁ is chosen, the remaining activities that are compatible with it are exactly those starting at or after f(g₁). An optimal answer for the full problem is g₁ plus an optimal answer for that subproblem. Applying the argument repeatedly, the greedy algorithm builds an optimal solution one choice at a time.
- The same two parts, greedy choice then optimal substructure, prove most greedy algorithms correct
Weighted Activity Selection
If every activity carries a weight (profit, priority, fee) and the goal is to maximise the total weight rather than the count, the greedy rule breaks. A single long, valuable activity can be worth more than three short cheap ones that finish earlier.
- Activities – A = [0, 3) worth 2, B = [2, 5) worth 4, C = [4, 7) worth 4, D = [0, 7) worth 7.
- Greedy by finish – picks A then C: weight 6.
- Optimal – D alone: weight 7.
The weighted version is solved with dynamic programming. Sort by finish time, and for each activity i find p(i), the last activity that finishes before i starts, with binary search. Then either skip i or take it with the best answer up to p(i). That gives O(n log n) overall. It is the same problem as maximum profit in job scheduling.
| Term | Meaning |
|---|---|
dp[i] | best total weight using only the first i activities |
p(i) | index of the last activity finishing at or before s(i) |
dp[i] = max(dp[i−1], w(i) + dp[p(i)]) | skip activity i, or take it |
- Unweighted: greedy by finish time. Weighted: DP with binary search. Both O(n log n)
Applications and Related Problems
The same algorithm schedules meetings in one room, lectures in one hall, jobs on one machine and bookings for one resource. The problem N meetings in one room is this algorithm verbatim.
Close relatives change the question slightly. Non-overlapping intervals asks for the fewest removals, which is n minus the activity selection answer. Interval partitioning asks for the fewest rooms needed to hold every activity, answered by sorting starts and tracking rooms in a min-heap, as in minimum number of platforms.
- Fewest intervals to remove = n − maximum compatible set
- Fewest rooms for all activities: interval partitioning, a different greedy