#1353

Maximum Number of Events That Can Be Attended

Medium
ArrayGreedySortingHeap (Priority Queue)GreedySortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach sorts the events by their end days and attends them in order, ensuring that we can maximize the number of events attended without overlap. This is efficient because it allows us to make greedy choices based on the earliest finishing event.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the events by their end day.
  2. 2Step 2: Initialize a counter for attended events and a variable to track the last attended day.
  3. 3Step 3: Iterate through the sorted events and for each event, check if the last attended day is less than the event's start day. If yes, attend the event on its start day or the last attended day + 1, and update the last attended day.
solution.py14 lines
1# Full working Python code
2
3def maxEvents(events):
4    events.sort(key=lambda x: x[1])
5    count = 0
6    last_day = 0
7    for start, end in events:
8        if last_day < start:
9            last_day = start
10            count += 1
11        elif last_day < end:
12            last_day += 1
13            count += 1
14    return count

Complexity note: The sorting step takes O(n log n) time, and the single pass through the events takes O(n) time, making this approach efficient overall.

  • 1Sorting events by end day allows us to make optimal choices for attending events.
  • 2Greedy algorithms work well when making local optimal choices leads to a global optimum.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.