|
| 1 | +public class 2402_Meeting_Rooms_III { |
| 2 | + |
| 3 | +} |
| 4 | +class Solution { |
| 5 | + public int mostBooked(int n, int[][] meetings) { |
| 6 | + Arrays.sort(meetings, (m1, m2) -> m1[0] == m2[0] ? m1[1] - m2[1] : m1[0] - m2[0]); |
| 7 | + |
| 8 | + PriorityQueue<Integer> freeRooms = new PriorityQueue<>(); // Index of free room indexes |
| 9 | + PriorityQueue<int[]> busyRooms = new PriorityQueue<>((r1, r2) -> r1[0] == r2[0] ? r1[1] - r2[1] : r1[0] - r2[0]); // Pair of {end time, room index} |
| 10 | + int[] count = new int[n]; |
| 11 | + |
| 12 | + for (int i = 0; i < n; i++) { |
| 13 | + freeRooms.offer(i); |
| 14 | + } |
| 15 | + |
| 16 | + for (int[] meeting : meetings) { |
| 17 | + int start = meeting[0], end = meeting[1]; |
| 18 | + |
| 19 | + while (!busyRooms.isEmpty() && busyRooms.peek()[0] <= start) { |
| 20 | + int roomIndex = busyRooms.poll()[1]; |
| 21 | + freeRooms.offer(roomIndex); |
| 22 | + } |
| 23 | + |
| 24 | + if (!freeRooms.isEmpty()) { |
| 25 | + int room = freeRooms.poll(); |
| 26 | + busyRooms.offer(new int[]{end, room}); |
| 27 | + count[room]++; |
| 28 | + } else { |
| 29 | + int[] nextAvailableRoom = busyRooms.poll(); |
| 30 | + int newEndingTime = nextAvailableRoom[0] + end - start; |
| 31 | + int roomIndex = nextAvailableRoom[1]; |
| 32 | + |
| 33 | + busyRooms.offer(new int[]{newEndingTime, roomIndex}); |
| 34 | + count[roomIndex]++; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + int maxCount = 0, result = 0; |
| 39 | + |
| 40 | + for (int i = 0; i < count.length; i++) { |
| 41 | + if (count[i] > maxCount) { |
| 42 | + maxCount = count[i]; |
| 43 | + result = i; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return result; |
| 48 | + } |
| 49 | +} |
0 commit comments