Maximum Number of Events That Can Be Attended

Medium

Topics
ArrayGreedyHeapSorting

Each row of grid is an event [startDay, endDay], meaning that event can be attended on any single day from startDay to endDay inclusive.

You attend at most one event per day, and attending an event takes the whole day. Return the maximum number of events you can attend.

LeetCode names the argument events; the harness here calls the table grid. Each row still has exactly two entries.

Example 1

14[1,2][2,3][3,4]
attended
Each lane is one event and spans the days it could be attended on, so a lane is a choice of day rather than a block of time that gets used up. You attend at most one event per day, which makes 3 events the most reachable out of 3 here. Every event fits, because no two of them are forced onto the same single day.
Only the count is returned, and several different schedules usually reach it.
Input:  grid = [[1,2],[2,3],[3,4]]
Output: 3
Explanation: Attend event 0 on day 1, event 1 on day 2 and event 2 on day 3.

Example 2

14[1,2][2,3][3,4][1,2]
attended
Input:  grid = [[1,2],[2,3],[3,4],[1,2]]
Output: 4
Explanation: Days 1, 2, 3 and 4 are each used once; the two [1,2] events take days 1 and 2.

Example 3

14[1,4][4,4][2,2][3,4][4,4]
attendedskipped
The dimmed 1 lane lost out because every day inside them was already spent on an event that had nowhere else to go.
Input:  grid = [[1,4],[4,4],[2,2],[3,4],[4,4]]
Output: 4
Explanation: There are five events but only four usable days, so one event must be skipped.

Constraints

  • 1 <= grid.length <= 10^5
  • grid[i].length == 2
  • 1 <= startDay <= endDay <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

The instinct is to sort by start day and take events in order, which fails: an event that starts early but runs for a long time should wait, because a day spent on it may be the only day another event could ever use.

Turn the question around and ask it day by day instead of event by event. On a given day, which of the events available today should you attend? The one that expires soonest. Any other choice risks losing that event entirely, while the one you postpone is still available tomorrow.

That exchange argument is what makes the rule safe: if an optimal plan attends a later-expiring event today and the soonest-expiring one some other day, swapping the two days keeps the plan valid and the same size.

So walk the days in order. Before choosing, make every event that has started available; then drop any that have already expired unattended, since they can never be used again. Among what remains, take the earliest end day.

Approach

  1. Sort the events by start day so they can be released in order as the day advances.
  2. Walk the days from the earliest start to the latest end. Maintain a collection of events that have started and not yet been attended, ordered by end day.
  3. At each day, add every event whose start day has arrived.
  4. Discard from the collection any event whose end day is already behind the current day — it was missed.
  5. If anything remains, attend the one with the smallest end day and count it.
  6. Skipping to the next interesting day rather than stepping through every calendar day avoids a long idle walk when the days are sparse.

Walkthrough

grid = [[1,4],[4,4],[2,2],[3,4],[4,4]]

sorted by start: [1,4] [2,2] [3,4] [4,4] [4,4]

day 1  available ends: {4}
       take end 4            -> attended [1,4], count 1
day 2  release [2,2], ends: {2}
       take end 2            -> attended [2,2], count 2
day 3  release [3,4], ends: {4}
       take end 4            -> attended [3,4], count 3
day 4  release [4,4] [4,4], ends: {4,4}
       take end 4            -> count 4
       the other [4,4] is left over; day 4 is used
day 5  the remaining event ended at 4, so it is discarded

answer 4, with five events and only four usable days

why earliest-end and not earliest-start
   on day 1, both [1,4] and (later) [2,2] compete.
   Choosing [1,4] on day 2 would strand [2,2], which
   can ONLY be attended on day 2.

Complexity

  • Time — O(n log n): each event is sorted once and enters and leaves the collection at most once.
  • Space — O(n): the collection can hold every event at once when they all start on the same day.

Common Pitfalls

  • Sorting by end day and attending greedily in that order. That is the rule for a different problem, where each event occupies its whole interval.
  • Choosing the event with the earliest start among those available. The deciding key is the end day.
  • Forgetting to discard expired events. They stay in the collection and get attended on a day after they ended.
  • Stepping one day at a time over the whole range. With days up to 100000 and few events, jumping to the next start day matters.
  • Advancing the day without counting, or counting without advancing. One event per day means both happen together.

Full Solution — all languages

class Solution:
    def maxEvents(self, grid):
        import heapq

        events = sorted(grid)                  # by start day
        heap = []                              # end days of started, unattended events
        i, day, count = 0, 0, 0
        n = len(events)

        while i < n or heap:
            if not heap:
                # Nothing available: jump straight to the next start day.
                day = max(day, events[i][0])

            while i < n and events[i][0] <= day:
                heapq.heappush(heap, events[i][1])
                i += 1

            # Anything that ended before today was missed for good.
            while heap and heap[0] < day:
                heapq.heappop(heap)

            if heap:
                heapq.heappop(heap)            # attend the soonest-expiring event
                count += 1
                day += 1

        return count
SensAI
Beta
Tap the mic to stop voice mode