Activity selection
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Activity selection maximises compatible events on a single resource by sorting intervals by finish time.
Why earliest finish time maximises compatible activities
Activity selection schedules competing tasks on one shared resource. Each task has a fixed start time and finish time. Two tasks conflict if their active time intervals overlap. Brute force tests every combination of tasks, requiring exponential time.
Step by step
Step 1 of 5
- lastEnd
- 2
- count
- 1
Example 1 · Brute force: try every subset of meetings, O(2^n * n^2)
public class Main { static boolean overlap(int[] a, int[] b) { return a[0] < b[1] && b[0] < a[1]; }
public static void main(String[] args) { int[][] meetings = {{1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}, {5, 9}}; int n = meetings.length; int best = 0;
for (int mask = 0; mask < (1 << n); mask++) { boolean ok = true; for (int i = 0; i < n && ok; i++) { if ((mask & (1 << i)) == 0) continue; for (int j = i + 1; j < n && ok; j++) { if ((mask & (1 << j)) != 0 && overlap(meetings[i], meetings[j])) ok = false; } } if (ok) best = Math.max(best, Integer.bitCount(mask)); } System.out.println("Maximum compatible meetings: " + best); }}Maximum compatible meetings: 4
What this code does
- Every subset of meetings is checked for any overlapping pair, and the largest valid subset wins.
- With n meetings there are 2^n subsets, so 30 meetings already means over a billion checks.
- Sorting by finish time gets the same answer in O(n log n).
Example 2 · Optimal: sort by finish time, O(n log n) time
import java.util.Arrays;
public class ActivitySelectionDemo { public static int maxMeetings(int[][] intervals) { if (intervals.length == 0) return 0; // Sort intervals by finish time in ascending order Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int count = 1; int lastEnd = intervals[0][1];
for (int i = 1; i < intervals.length; i++) { if (intervals[i][0] >= lastEnd) { count++; lastEnd = intervals[i][1]; } } return count; }
public static void main(String[] args) { int[][] meetings = { {1, 2}, {3, 4}, {0, 6}, {5, 7}, {8, 9}, {5, 9} }; System.out.println("Maximum compatible meetings: " + maxMeetings(meetings)); }}Maximum compatible meetings: 4
What this code does
- Uses Integer.compare to sort intervals by finish time without integer overflow.
- Selects meeting [1, 2], then [3, 4], skips [0, 6], selects [5, 7], and selects [8, 9].
- Yields four mutually compatible meetings running in O(n log n) time.
- After sorting, one scan picks each meeting that fits, so the 2^n subsets never have to be tried.
A greedy strategy sorts all activities by their finish times. Selecting the task that finishes earliest frees the resource as soon as possible. This leaves the maximum remaining time window for future activities. After picking the first task, scan through the remaining sorted tasks. Accept any task whose start time is at or after the previous finish time. Skip any task that starts before the current finish time. This greedy algorithm runs in log-linear time dominated by sorting.
Why alternative sorting strategies fail
An alternative sort key, such as start time or duration, looks as reasonable as end time. However, both alternative heuristics fail on simple counter-examples, and only the comparator differs (shown after the code).
int[][] tasks = {{0, 10}, {9, 11}, {10, 20}};// Correct: earliest end first -> picks {0, 10} and {10, 20} = 2 tasksArrays.sort(tasks, (a, b) -> a[1] - b[1]);// Wrong: earliest start first -> a long {0, 100} task blocks everythingArrays.sort(tasks, (a, b) -> a[0] - b[0]);// Wrong: shortest first -> picks {9, 11}, which blocks both others = 1 taskArrays.sort(tasks, (a, b) -> (a[1] - a[0]) - (b[1] - b[0]));Sorting by start time can pick a long task that blocks many others. For example, a task from 0 to 100 starts earliest. Selecting it blocks ten short tasks running between 1 and 99.
Sorting by shortest duration also fails. Consider three tasks: 0 to 10, 9 to 11, and 10 to 20. The shortest task runs from 9 to 11 with duration 2. Choosing it blocks both adjacent tasks, yielding only one task. Selecting tasks 0 to 10 and 10 to 20 yields two tasks.
Predict the output
Predict the greedy count
Read the code and pick what it prints.
Two sort keys, one task list. What does this program print?
Bursting balloons and interval duals
Bursting balloons with minimum arrows is equivalent to activity selection. Each balloon represents a closed interval along a coordinate axis. An arrow shot at coordinate x bursts all balloons covering x.
Example 3 · Minimum Arrows to Burst Balloons
import java.util.Arrays;
public class MinArrowsBalloonsDemo { public static int findMinArrowShots(int[][] points) { if (points.length == 0) return 0; Arrays.sort(points, (a, b) -> Integer.compare(a[1], b[1]));
int arrows = 1; int arrowPos = points[0][1];
for (int i = 1; i < points.length; i++) { if (points[i][0] > arrowPos) { arrows++; arrowPos = points[i][1]; } } return arrows; }
public static void main(String[] args) { int[][] balloons = { {10, 16}, {2, 8}, {1, 6}, {7, 12} }; System.out.println("Minimum arrows: " + findMinArrowShots(balloons)); }}Minimum arrows: 2
What this code does
- Sorts balloons by end position: [1, 6], [2, 8], [7, 12], [10, 16].
- First arrow at 6 bursts [1, 6] and [2, 8].
- Second arrow at 12 bursts [7, 12] and [10, 16], requiring 2 arrows in total.
Example 4 · Minimum Removals for Non-Overlapping Intervals
import java.util.Arrays;
public class EraseOverlapIntervalsDemo { public static int eraseOverlapIntervals(int[][] intervals) { if (intervals.length == 0) return 0; Arrays.sort(intervals, (a, b) -> Integer.compare(a[1], b[1]));
int compatible = 1; int lastEnd = intervals[0][1];
for (int i = 1; i < intervals.length; i++) { if (intervals[i][0] >= lastEnd) { compatible++; lastEnd = intervals[i][1]; } } return intervals.length - compatible; }
public static void main(String[] args) { int[][] intervals = {{1, 2}, {2, 3}, {3, 4}, {1, 3}}; System.out.println("Minimum removals: " + eraseOverlapIntervals(intervals)); }}Minimum removals: 1
What this code does
- Finds the maximum set of compatible intervals using earliest finish time.
- Subtracts compatible count from total intervals to determine minimum removals.
- Removing interval [1, 3] leaves [1, 2], [2, 3], and [3, 4] with no overlaps.
To minimise arrows, sort all balloons by their end coordinate. Shoot the first arrow at the end of the first balloon. This arrow covers as many overlapping balloons as possible. Any balloon starting before or at the arrow position is already burst. When encountering a balloon starting after the arrow, shoot a new arrow. Place the new arrow at the end coordinate of that balloon. The minimum arrows needed equals the maximum count of mutually disjoint intervals.
Next step
Check your understanding
10 quick questions