medium +20 pts

Max events attended

Schedule non-overlapping events to maximize the number you can attend.

You are given a list of events. Each event is a tuple (start, end) where start is the start time and end is the end time (inclusive). You can attend an event if it does not overlap with any other attended event. Two events overlap if they share any time slot. For example, (1,3) and (3,5) are considered overlapping because time 3 is shared. Write a function `max_events(events)` that returns the maximum number of events you can attend without overlap. **Input:** A list of tuples, each tuple (start, end) with 0 <= start <= end <= 10^9. The list may be empty. **Output:** An integer, the maximum number of non-overlapping events. **Note:** The order of the list does not matter. You can choose any subset of events as long as they are pairwise non-overlapping.

Constraints

- 0 <= len(events) <= 10^5 - 0 <= start <= end <= 10^9 - Aim for O(n log n) time, O(n) space worst-case.

Example

>>> max_events([]) 
0
>>> max_events([(1,3), (3,5), (6,8)]) 
2
>>> max_events([(1,2), (2,3), (3,4), (4,5)]) 
2
>>> max_events([(1,5), (2,3), (4,6), (7,8)]) 
3
20 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Sort events by their end time.
Greedily pick the earliest-ending event that starts after the last chosen event's end.
Remember that events are inclusive on both ends, so the next start must be greater than the previous end.
If two events have the same end time, any order works for the greedy choice.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.