Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

On a given day, attending the available event that ends soonest leaves more flexible events for later. If an optimal schedule chose a later-ending available event instead, swapping in the earliest-ending one cannot prevent moving that other event to the later slot.

Approach

Sort events by start day and scan calendar days through the largest end day. Add events starting today to a min-heap of end days, discard expired entries, and attend one event by removing the smallest remaining end day. Count attended events and stop early when no pending or future events remain. End days are inclusive: an event expiring today is still available. The reference implementations scan days rather than jumping across empty stretches.

class Solution: def maxEvents(self, events: List[List[int]]) -> int: mx = max(e for s, e in events) events.sort() res = 0 pq = [] j = 0 for i in range(1, mx + 1): while j < len(events) and events[j][0] == i: heapq.heappush(pq, events[j][1]) j += 1 while pq and i > pq[0]: heapq.heappop(pq) if pq and i <= pq[0]: heapq.heappop(pq) res += 1 if not pq and j == len(events): break # for optimization return res

Complexity analysis

Let E be the event count and D the largest ending day. Both displayed implementations sort the events and scan each day through D, using O(E log E + D) time and O(E) auxiliary heap/sort space.