Problem
You are given an array of events
where events[i] = [startDayi, endDayi]
. Every event i
starts at startDayi
and ends at endDayi
.
You can attend an event i
at any day d
where startTimei <= d <= endTimei
. You can only attend one event at any time d
.
Return the maximum number of events you can attend.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= events.length <= 105
events[i].length == 2
1 <= startDayi <= endDayi <= 105
Solution
Method 1 – Greedy with Min Heap
Intuition
To maximize the number of events attended, always attend the event that ends earliest among all available events for each day. By using a min-heap to track the end days of available events, we can efficiently pick the next event to attend and skip days/events that are no longer possible.
Approach
- Sort the events by their start day.
- Initialize a min-heap to keep track of end days of events that can be attended on the current day.
- For each day from the earliest start to the latest end:
- Add all events starting on this day to the heap.
- Remove events from the heap that have already ended.
- If the heap is not empty, attend the event with the earliest end day (pop from heap), and increment the answer.
- Continue until all events are processed.
- Return the total number of events attended.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Method 2 – Segment Tree (Range Query)
Intuition
We can use a segment tree to efficiently find the earliest available day to attend an event in its interval. For each event, we query the segment tree for the minimum available day in its range, and if found, mark that day as used. This allows us to maximize the number of events attended.
Approach
- Sort events by their end day (to prioritize earliest finishing events).
- Build a segment tree to track available days (1 for available, 0 for used) in the range [1, max end day].
- For each event, query the segment tree for the minimum available day in [start, end].
- If a day is found, mark it as used in the segment tree and increment the answer.
- Return the total number of events attended.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log D)
, where n is the number of events and D is the range of days. Each query/update is O(log D). - 🧺 Space complexity:
O(D)
, for the segment tree.