Problem Link

Description


You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.

You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.

Return the maximum number of events you can attend.

 

Example 1:

Input: events = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: You can attend all the three events.
One way to attend them all is as shown.
Attend the first event on day 1.
Attend the second event on day 2.
Attend the third event on day 3.

Example 2:

Input: events= [[1,2],[2,3],[3,4],[1,2]]
Output: 4

 

Constraints:

  • 1 <= events.length <= 105
  • events[i].length == 2
  • 1 <= startDayi <= endDayi <= 105

Solution


Python3

class Solution:
    def maxEvents(self, events: List[List[int]]) -> int:
        N = len(events)
        events.sort()
        res = index = 0
        heap = []
        maxDays = max(end for _, end in events)
 
        for day in range(1, maxDays + 1):
            while index < N and events[index][0] == day:
                heappush(heap, events[index][1])
                index += 1
            
            while heap and day > heap[0]:
                heappop(heap)
            
            if heap:
                heappop(heap)
                res += 1
 
        return res

C++

class Solution {
public:
    int maxEvents(vector<vector<int>>& A) {
        priority_queue <int,vector<int>,greater<int>> pq;
        sort(A.begin(), A.end());
        int i = 0, res = 0, n = A.size();
        for (int d = 1; d <= 100000; d++){
            while (pq.size() && pq.top() < d)
                pq.pop();
                
            while (i < n && A[i][0] == d)
                pq.push(A[i++][1]);
            
            if (pq.size()){
                pq.pop();
                ++res;
            }
        }
        
        return res;
    }
};