Problem Description
Given an array of events where each event is defined by a start day and an end day, determine the maximum number of events you can attend with the constraint that you can attend at most one event per day. An event can be attended on any day within its start and end period (inclusive).
Key Insights
- Sort events by their start day.
- Use a min-heap (priority queue) to dynamically store events that have started but not yet ended.
- On each day, add all events starting on that day to the heap.
- Remove events from the heap that have already ended.
- Always attend the event that ends the earliest (pop from the heap) to free up future days.
- Iteratively move through each day until all events are processed.
Space and Time Complexity
Time Complexity: O(n log n)
Space Complexity: O(n)
Solution
The algorithm starts by sorting the events by their start day. Then, using a min-heap, it processes each day from the earliest start day up to the latest possible day among the events. For each day, it adds all events that begin on that day into the min-heap. The heap is used to keep track of the current events by their end days. Events that have ended before the current day are removed from the heap. On each day, if there is any event in the heap, the one with the smallest end day (which gives the best chance for future days) is attended and removed from the heap. This greedy strategy maximizes the total number of events attended.