Meeting Rooms II in C++

C++Server Side ProgrammingProgramming

Suppose there is an array of meeting time intervals. There are two times start and end times [[s1,e1],[s2,e2],...] and each pair satisfies the rule (si < ei), We have to find the minimum number of conference rooms required.

So, if the input is like [[0, 30], [5, 10], [15, 20]], then the output will be 2.

To solve this, we will follow these steps −

  • define one priority queue pq

  • sort the intervals array

  • ret := 0

  • for initialize i := 0, when i < size of intervals, update (increase i by 1), do −

    • while (not pq is empty and top element of pq <= intervals[i, 0]), do −

      • delete element from pq

    • insert intervals[i] into pq

    • ret := maximum of ret and size of pq

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Comparator{
   bool operator()(vector <int<& a, vector <int<& b){
      return !(a[1] < b[1]);
   }
};
class Solution {
public:
   static bool cmp(vector <int< a, vector <int< b){
      return (a[1] < b[1]);
   }
   int minMeetingRooms(vector<vector<int<>& intervals) {
      priority_queue<vector<int<, vector<vector<int< >, Comparator> pq;
      sort(intervals.begin(), intervals.end());
      int ret = 0;
      for (int i = 0; i < intervals.size(); i++) {
         while (!pq.empty() && pq.top()[1] <= intervals[i][0])
         pq.pop();
         pq.push(intervals[i]);
         ret = max(ret, (int)pq.size());
      }
      return ret;
   }
};
main(){
   vector<vector<int<> v = {{0, 30}, {5, 10}, {15, 20}};
   Solution ob;
   cout << (ob.minMeetingRooms(v));
}

Input

{{0, 30}, {5, 10}, {15, 20}}

Output

2
raja
Updated on 18-Nov-2020 11:30:42

Advertisements