Problem Statement
Maximum Number of Events That Can Be Attended
You are given a list of events. Each event looks like events[i] = [startDay, endDay], which means that event is open from startDay until endDay. You can show up to an event on any single day d as long as startDay <= d <= endDay. But you can only attend one event per day, so you have to pick carefully. The goal is to attend as many different events as possible. The trick: sort the events by their start day, keep a min-heap of the end days of the events that are currently open, and each day attend the open event that ends the soonest. A min-heap is like a basket that always keeps the smallest number on top, so you can grab the soonest-to-expire event instantly. We attend the soonest-ending event first because it has the least room left to be attended later, so saving it for later risks losing it.
Signals to notice
Brute force first
Try all assignments of events to days — exponential. Each event-day pair is a choice. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.
The key insight
Sort events by start day. For each day, add all events starting on that day to a min-heap (by end day). Attend the event ending soonest (pop heap). Skip expired events. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.
Trace it on events=[[1,2],[2,3],[3,4],[1,2]]
sort -> [[1,2],[1,2],[2,3],[3,4]]; max_day=4, day=1, heap=[], count=0, i=0 day=1: push starts==1 -> heap=[2,2], i=2; none expired; pop 2 -> count=1, heap=[2] day=2: push start==2 -> heap=[2,3], i=3; none expired; pop 2 -> count=2, heap=[3] day=3: push start==3 -> heap=[3,4], i=4; none expired; pop 3 -> count=3, heap=[4] day=4: no new events; none expired; pop 4 -> count=4, heap=[] day=5 > max_day -> loop ends; return count=4
What must stay true
On each day, attending the event with the earliest deadline maximizes future flexibility — it's the event you're most at risk of losing. Events with later deadlines can still be attended tomorrow. If that remains true after every update, the rest of the reasoning has a stable place to stand.
Shape of the loop
sort events by start day; heap = min-heap of end days for day from first_start to max_end: push end-day of every event whose start == day while heap.top < day: pop # expired, can't attend if heap: pop earliest deadline; count += 1 return count
Pseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Attending events in order of start day instead of deadline — an event starting early but ending late should be deferred if another event is about to expire. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.