Maximum Number of Events That Can Be Attended Problem
Description
LeetCode Problem 1353.
You are given an array of events where events[i] = [startDay_i, endDay_i]. Every event i starts at startDay_iand ends at endDay_i.
You can attend an event i at any day d where startDay_i <= d <= endDay_i. 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 <= 10^5events[i].length == 21 <= startDay_i <= endDay_i <= 10^5
Solution
Approach: Greedy Day Sweep with a Min-Heap
Go through the days in order, and on each day attend one event, choosing among the events that are open today the one that ends first. The others can still be attended later, while the one ending first has the least time left, so taking it never hurts: if an optimal plan attends a different event x today, swapping it with the earliest-ending event y (which the plan attends later or not at all) still gives a valid plan of the same size.
To find that event quickly:
- Sort the events by start day.
- For each day
dfrom1to the last end day, push the end days of the events starting ondinto a min-heap. - Pop the end days smaller than
d: those events are over and can no longer be attended. - If the heap is not empty, pop its smallest end day: that is the event attended today, so add one to the answer.
The heap holds end days only, since the start day of an event in the heap has already passed. Several events with the same day range, like [1,2] twice in Example 2, are separate heap entries and can be attended on different days.
Complexity: O(n log n + D) time, where D <= 10^5 is the last end day: every event is pushed and popped once. O(n) extra space.
import heapq
class Solution:
def maxEvents(self, events: List[List[int]]) -> int:
events.sort() # by start day
ends = [] # min-heap of the end days of events that have started
ans = i = 0
last_day = max(e for _, e in events)
for day in range(1, last_day + 1):
while i < len(events) and events[i][0] == day:
heapq.heappush(ends, events[i][1])
i += 1
while ends and ends[0] < day:
heapq.heappop(ends) # already over
if ends:
heapq.heappop(ends) # attend the open event that ends first
ans += 1
return ans