Minimum Meeting Rooms
Problem
Each meeting has a start and an end time. A meeting [s, e) uses a room from s until just before e, so one meeting may start exactly when another ends in the same room. Print the smallest number of rooms needed for all meetings. Input: n and 2, then n rows with the start and end of each meeting.
Constraints
- 1 <= n <= 10^4
- 0 <= start < end <= 10^6
Examples
Input
3 2 0 30 5 10 15 20
Output
2
Solutions
The sorted ends tell us when the first room becomes free. If the next meeting starts after that time, it takes the room; otherwise a new room is needed. O(n log n) because of sorting.
/*
* Problem : Meeting rooms.
* Input : n, 2, then n rows.
* Output : Number of rooms.
* Approach: Sorted starts and ends.
* Time : O(n log n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[][] m) {
// Step 1: Put all start times in one sorted array and all end times in another.
int n = m.length;
int[] starts = new int[n];
int[] ends = new int[n];
for (int i = 0; i < n; i++) {
starts[i] = m[i][0];
ends[i] = m[i][1];
}
java.util.Arrays.sort(starts);
java.util.Arrays.sort(ends);
// Step 2: Go through the starts. If the earliest unfinished meeting has ended, reuse its room. Otherwise open a new room.
int rooms = 0;
int endIndex = 0;
for (int i = 0; i < n; i++) {
if (starts[i] >= ends[endIndex]) {
endIndex++;
} else {
rooms++;
}
}
return rooms;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] m = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
m[i][j] = scanner.nextInt();
}
}
System.out.println(solve(m));
}
}
Hints (2)
- What does ends[endIndex] mean?
- When must we open a new room?