# 2402. Meeting Rooms III



````java
```java
class Solution {
    class Meeting {
        int end;
        int roomId;
        Meeting(int end, int roomId) {
            this.end = end;
            this.roomId = roomId;
        }
    }
    public int mostBooked(int n, int[][] meetings) {
        Arrays.sort(meetings, (a, b) -> a[0] - b[0]); // sort by start
        Queue<Meeting> processMeetings = new PriorityQueue<>((a, b) -> a.end == b.end ? a.roomId - b.roomId : a.end - b.end);
        Queue<Integer> availableRooms = new PriorityQueue<>();
        for (int i = 0; i < n; i++) {
            availableRooms.add(i); // add all rooms to availability
        }

        int[] roomCount = new int[n];
        int roomId = 0;
        for (int[] m: meetings) {
            int startTime = m[0];
            int endTime = m[1];

            while (!processMeetings.isEmpty() && startTime >= processMeetings.peek().end) {
                availableRooms.add(processMeetings.poll().roomId); // 退出會議, 加到可用的
            } 
            if (availableRooms.size() == 0) { // 沒有任何可用的, 代表會延後時間開始會議
                Meeting finsihedMeeting = processMeetings.poll();
                endTime = finsihedMeeting.end + (endTime - startTime);
                availableRooms.add(finsihedMeeting.roomId);
            }

            int newRoomUsed = availableRooms.poll(); // from all availableRooms to select which room we use
            processMeetings.offer(new Meeting(endTime, newRoomUsed));
            roomCount[newRoomUsed]++;
        }

        int max = 0;
        int result = -1;
        for (int i = 0; i < n; i++) {
            //System.out.println("romm:" + i + ",count: "+ roomCount[i]);
            if (roomCount[i] > max) {
                max = roomCount[i];
                result = i; // 這樣就取小的會議號碼
            }
        }
        return result;
    }
}

/**

0            10 used
             3 4
                (11) 
  1.   5.  used
       2.    7
             (10)     
      

1                  20 used
  2         10. used
    3. 5.       used roo2
       4.    9(10) 
             6 8(12)     roo1



             sort by start -> one by one exec
             min heap poll the end time smaller one, add to heap...


             class start end roomId


             0             10.  room 0
               1 2. room1
                                12. 14 room 1 -> should use room 0
                                  13   15. room0
 */
```
````
