Maximum Number of Events That Can Be Attended in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of events where events[i] = [startDayi, endDayi]. Here every event I start at startDayi and ends at endDayi. We can attend an event I at any day d where d in range startTimei and endTimei (both inclusive). We have to keep in mind that we can only attend one event at any time. So find the maximum number of events we can attend. So for example, if the input is like [[1,4], [4,4], [2,2], [3,4], [1,1]], then the output will be 1, as we can attend maximum of four events, these are [1, 1], [2, 2], [3, 4] and [4, 4].

To solve this, we will follow these steps −

  • n := number of events, then sort the event list based on the start date, set ret := 0 and itr := 0

  • create a priority queue based on max-heap called pq

  • for I in range 1 to 10000

    • while itr < n and events[itr, 0] = i

      • insert events[itr, 1]

      • increase itr by 1

    • while pq is not empty and top of pq < i,

      • delete element from pq

    • if pq is not empty, then delete from pq and increase ret by 1

  • return ret

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   static bool cmp(vector <int>& a, vector <int>& b){
      return a[0] < b[0];
   }
   int maxEvents(vector<vector<int>>& events) {
      int n = events.size();
      sort(events.begin(), events.end(), cmp);
      int ret = 0;
      int itr = 0;
      priority_queue <int, vector <int>, greater <int>> pq;
      for(int i = 1; i <= 1e5; i++){
         while(itr < n && events[itr][0] == i){
            pq.push(events[itr][1]);
            itr++;
         }
         while(!pq.empty() && pq.top() < i) pq.pop();
         if(!pq.empty()){
            pq.pop();
            ret++;
         }
      }
      return ret;
   }
};
main(){
   vector<vector<int>> v = {{1,4},{4,4},{2,2},{3,4},{1,1}};
   Solution ob;
   cout << (ob.maxEvents(v));
}

Input

[[1,4],[4,4],[2,2],[3,4],[1,1]]

Output

4
raja
Published on 31-Mar-2020 07:51:39
Advertisements