Maximum Number of Events That Can Be Attended

Similar Problems:

- CheatSheet: LeetCode For Code Interview
- CheatSheet: Common Code Problems & Follow-ups
- Tag: #heap, #greedy, #meetingconflict

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.

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 <= 10^5
- events[i].length == 2
- 1 <= events[i][0] <= events[i][1] <= 10^5
- Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

## https://code.dennyzhang.com/maximum-number-of-events-that-can-be-attended ## Basic Ideas: soring + heap + greedy ## ## Sort by starting time. And always take the early one ## ## If several meetings start with the same day, we can assume always choose one ## ## Complexity: Time O(n*log(n)), Space O(n) class Solution: def maxEvents(self, events: List[List[int]]) -> int: events.sort() l = [] res = 0 i = 0 for d in range(1, 100001): # cleanup finished meetings while len(l) > 0 and l[0] < d: heapq.heappop(l) # meetings start with the same day while i<len(events) and events[i][0] == d: heapq.heappush(l, events[i][1]) i += 1 # take one meeting if len(l) > 0: heapq.heappop(l) res += 1 return res