Link: https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended
| Date | Stopwatch | Y/N | Feedback |
|---|---|---|---|
| Jul 10, 2025 | 27m | Y |
Edge Case:
Input: eventws = [[1,2],[1,2],[3,3],[1,5],[1,5]]
Output: 5
-
For interval type question, it is a good habit to sort first.
-
Find the max_end_day from
events, so we can loop over dayiin[1, max_end_day]. For each dayi, we are addingstart_day < ifromevents, and weheappush()event[j]'send_dayintominHeap, otherwise, the start_day won't help us to keep the correct order inminHeap(edge case). -
Check minHeap's end_day from the top of minHeap, if
minHeap[0] < i, we need to remove this event fromminHeap, because we will not be able to take this event after dayi. -
Lastly, if
minHeapis not empty, we take this current event in the top ofminHeapand incrementans += 1.
class Solution:
def maxEvents(self, events: List[List[int]]) -> int:
# 1. Sort events and find max end day from events
# 2. Loop over each day i [0, max_day+1], and add days into minHeap if start <= i, also exclude end_day in minHeap < i
# TC: O(nlog(n) + nlog(k)), n=len(events), k=len(minHeap), SC: O(k)
events = sorted(events)
j = 0 # event index
ans = 0
minHeap = []
max_day = max(event[1] for event in events)
# Loop over each day i
for i in range(1, max_day + 1):
# Add start_day < i into minHeap
while j < len(events) and events[j][0] <= i:
# Only add the end_day into minHeap, otherwise we can't keep the correct order in minHeap
heapq.heappush(minHeap, events[j][1])
j += 1
# Remove previous end_day < i from minHeap
while minHeap and minHeap[0] < i:
heapq.heappop(minHeap)
# Increment ans assume we attend the meeting in the top of minHeap
if minHeap:
ans += 1
heapq.heappop(minHeap)
return ansTime Complexity: O(nlog(n)) for sorting events, O(nlog(k)) for heap operation on each day.
Space Complexity: