Maximum Number of Events That Can Be Attended
Medium
Topics
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
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
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
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
- Sort the events by start day so they can be released in order as the day advances.
- 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.
- At each day, add every event whose start day has arrived.
- Discard from the collection any event whose end day is already behind the current day — it was missed.
- If anything remains, attend the one with the smallest end day and count it.
- 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 countimport java.util.*;
class Solution {
public int maxEvents(int[][] grid) {
int[][] events = new int[grid.length][];
for (int i = 0; i < grid.length; i++) events[i] = grid[i].clone();
Arrays.sort(events, (x, y) -> Integer.compare(x[0], y[0]));
PriorityQueue<Integer> ends = new PriorityQueue<>();
int i = 0, day = 0, count = 0, n = events.length;
while (i < n || !ends.isEmpty()) {
if (ends.isEmpty()) day = Math.max(day, events[i][0]);
while (i < n && events[i][0] <= day) ends.add(events[i++][1]);
while (!ends.isEmpty() && ends.peek() < day) ends.poll();
if (!ends.isEmpty()) {
ends.poll();
count++;
day++;
}
}
return count;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxEvents(vector<vector<int>>& grid) {
vector<vector<int>> events = grid;
sort(events.begin(), events.end());
priority_queue<int, vector<int>, greater<int>> ends;
int i = 0, day = 0, count = 0, n = (int)events.size();
while (i < n || !ends.empty()) {
if (ends.empty()) day = max(day, events[i][0]);
while (i < n && events[i][0] <= day) ends.push(events[i++][1]);
while (!ends.empty() && ends.top() < day) ends.pop();
if (!ends.empty()) {
ends.pop();
count++;
day++;
}
}
return count;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var maxEvents = function(grid) {
const events = grid.map((e) => e.slice()).sort((x, y) => x[0] - y[0]);
const n = events.length;
// A sorted array stands in for a priority queue; n is small enough here
// that the insert cost does not matter.
const ends = [];
const push = (v) => {
let lo = 0, hi = ends.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (ends[mid] < v) lo = mid + 1;
else hi = mid;
}
ends.splice(lo, 0, v);
};
let i = 0, day = 0, count = 0;
while (i < n || ends.length) {
if (!ends.length) day = Math.max(day, events[i][0]);
while (i < n && events[i][0] <= day) push(events[i++][1]);
while (ends.length && ends[0] < day) ends.shift();
if (ends.length) {
ends.shift();
count++;
day++;
}
}
return count;
};