Skip to content

Latest commit

 

History

History

1353

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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. Notice that 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

Example 3:

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

Example 4:

Input: events = [[1,100000]]
Output: 1

Example 5:

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

 

Constraints:

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

Companies:
Microsoft, Infosys

Related Topics:
Greedy, Sort, Segment Tree

Similar Questions:

Solution 1. Greedy

Sort the events in ascending order of the start time.

Let day be the current day and it starts with A[0][0].

If an event starts at day, we start to take it into consideration.

If an event ends before day, we can ignore it.

If an event starts no later than day and ends after day, we call it an active event.

Use a priority_queue to keep track of the end times of active events, and greedily pick the event with the earliest end time.

Here is a very good article explaining the reasoning step by step.

// OJ: https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
// Ref: https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/discuss/510263/JavaC%2B%2BPython-Priority-Queue
class Solution {
public:
    int maxEvents(vector<vector<int>>& A) {
        sort(A.begin(), A.end());
        priority_queue<int, vector<int>, greater<>> pq;
        int N = A.size(), i = 0, day = A[0][0], ans = 0;
        while (i < N || pq.size()) {
            if (pq.empty()) day = A[i][0]; // If no active event is available and there are still more events to pick, jump to the start date of the next event.
            while (i < N && A[i][0] == day) pq.push(A[i++][1]); // add events that start at `day` as active events, push their end time into queue
            pq.pop(); // pick the event with the earliest start time
            ++ans;
            ++day;
            while (pq.size() && pq.top() < day) pq.pop(); // ignore the events that are no longer active
        }
        return ans;
    }
};

Note

Similar to 1834. Single-Threaded CPU (Medium)