N meetings in one room
Pattern: Activity selection
Sort by finishing time and keep taking the next meeting that starts strictly after the last chosen one ends. Finishing as early as possible leaves the most room for the rest, so this keeps the largest count.
The problem
Given the start and end times of meetings, return the largest number that can be held in one room, where a meeting
must start strictly after the previous one ends. start = [1, 3, 0, 5, 8, 5], end = [2, 4, 6, 7, 9, 9] gives 4.
Think first
- Which meeting should go first in a best schedule?
- After choosing it, what problem is left?
- Do touching meetings clash here?
Hints
Brute force, and why it fails
Try every subset: O(2ⁿ × n).
The key insight
If a best schedule starts with some meeting other than the earliest finisher, swap it for the earliest finisher: nothing else clashes, and the count is the same. So the earliest finisher is always safe.
Dry run
| lastEnd | none |
|---|
start [1, 3, 0, 5, 8, 5], end [2, 4, 6, 7, 9, 9]. Sorted by end: (1, 2), (3, 4), (0, 6), (5, 7), (8, 9), (5, 9).
The plan
sort by end
lastEnd = -infinity
for (s, e): if s > lastEnd: count += 1; lastEnd = e
Complexity
- Time
O(n log n)- Space
O(n)
Sorting dominates; the scan is linear.
Edge cases
- Meetings that touch (start equal to the last end) clash here.
- One meeting.
- All overlapping: 1.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int maxMeetings(int[] start, int[] end) {
int n = start.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> Integer.compare(end[a], end[b])); // earliest finish first
int count = 0, lastEnd = Integer.MIN_VALUE;
for (int i : order) {
if (start[i] > lastEnd) { // starts strictly after the last chosen one ends
count++;
lastEnd = end[i];
}
}
return count;
}
}C++
class Solution {
public:
int maxMeetings(vector<int>& start, vector<int>& end) {
int n = static_cast<int>(start.size());
vector<int> order(n);
for (int i = 0; i < n; i++) order[i] = i;
sort(order.begin(), order.end(), [&](int a, int b) { return end[a] < end[b]; }); // earliest finish first
int count = 0;
long long lastEnd = LLONG_MIN;
for (int i : order) {
if (start[i] > lastEnd) { // starts strictly after the last chosen one ends
count++;
lastEnd = end[i];
}
}
return count;
}
};Python
class Solution:
def maxMeetings(self, start: list[int], end: list[int]) -> int:
count, last_end = 0, float("-inf")
for s, e in sorted(zip(start, end), key=lambda p: p[1]): # earliest finish first
if s > last_end: # starts strictly after the last chosen one ends
count += 1
last_end = e
return countCommon mistakes
- Sorting by start time: an early, long meeting blocks many short ones.
- Using
>=when the problem says a new meeting must start after the last one ends.