-
Notifications
You must be signed in to change notification settings - Fork 1
/
MinimumMeetingRooms.java
79 lines (69 loc) · 2.55 KB
/
MinimumMeetingRooms.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.util.*;
class Meeting {
int start;
int end;
public Meeting(int start, int end) {
this.start = start;
this.end = end;
}
};
class MinimumMeetingRooms {
public static int findMinimumMeetingRooms(List<Meeting> meetings) {
if (meetings == null || meetings.size() == 0)
return 0;
// sort the meetings by start time
Collections.sort(meetings, (a, b) -> Integer.compare(a.start, b.start));
int minRooms = 0;
PriorityQueue<Meeting> minHeap =
new PriorityQueue<>(meetings.size(), (a, b) -> Integer.compare(a.end, b.end));
for (Meeting meeting : meetings) {
// remove all meetings that have ended
while (!minHeap.isEmpty() && meeting.start >= minHeap.peek().end)
minHeap.poll();
// add the current meeting into the minHeap
minHeap.offer(meeting);
// all active meeting are in the minHeap, so we need rooms for all of them.
minRooms = Math.max(minRooms, minHeap.size());
}
return minRooms;
}
public static void main(String[] args) {
List<Meeting> input = new ArrayList<Meeting>() {
{
add(new Meeting(1, 4));
add(new Meeting(2, 5));
add(new Meeting(7, 9));
}
};
int result = MinimumMeetingRooms.findMinimumMeetingRooms(input);
System.out.println("Minimum meeting rooms required: " + result);
input = new ArrayList<Meeting>() {
{
add(new Meeting(6, 7));
add(new Meeting(2, 4));
add(new Meeting(8, 12));
}
};
result = MinimumMeetingRooms.findMinimumMeetingRooms(input);
System.out.println("Minimum meeting rooms required: " + result);
input = new ArrayList<Meeting>() {
{
add(new Meeting(1, 4));
add(new Meeting(2, 3));
add(new Meeting(3, 6));
}
};
result = MinimumMeetingRooms.findMinimumMeetingRooms(input);
System.out.println("Minimum meeting rooms required: " + result);
input = new ArrayList<Meeting>() {
{
add(new Meeting(4, 5));
add(new Meeting(2, 3));
add(new Meeting(2, 4));
add(new Meeting(3, 5));
}
};
result = MinimumMeetingRooms.findMinimumMeetingRooms(input);
System.out.println("Minimum meeting rooms required: " + result);
}
}