Maximum Number of Events That Can Be Attended - 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 startDayi ≤ d ≤ endDayi. You can only attend one event at any time d.

Return the maximum number of events you can attend.

Input & Output

Example 1 — Basic Case
$ Input: events = [[1,2],[2,3],[3,4]]
Output: 3
💡 Note: We can attend all three events: attend event [1,2] on day 1, event [2,3] on day 2, and event [3,4] on day 3.
Example 2 — Overlapping Events
$ Input: events = [[1,2],[2,3],[3,4],[1,2]]
Output: 4
💡 Note: We can attend all four events: attend first [1,2] on day 1, [2,3] on day 2, [3,4] on day 3, and second [1,2] on day 2. Wait, that's wrong - we can't attend two events on day 2. Actually, we attend first [1,2] on day 1, second [1,2] on day 2, [2,3] on day 3, and [3,4] on day 4.
Example 3 — Single Day Events
$ Input: events = [[1,4],[4,4],[1,4],[1,4]]
Output: 4
💡 Note: We can attend event [1,4] on days 1, 2, 3, and the [4,4] event on day 4, for a total of 4 events.

Constraints

  • 1 ≤ events.length ≤ 105
  • events[i].length == 2
  • 1 ≤ startDayi ≤ endDayi ≤ 105

Visualization

Tap to expand
Maximum Events That Can Be Attended INPUT Events Timeline: Day: 1 2 3 4 Event 1 [1,2] Event 2 [2,3] Event 3 [3,4] Input Array: [[1,2],[2,3],[3,4]] Events can overlap! Day 2: Events 1 and 2 Day 3: Events 2 and 3 ALGORITHM STEPS 1 Sort by Start Sort events by startDay 2 Use Min-Heap Track endDays in heap 3 Process Daily For each day, add new events 4 Attend Earliest Pop min endDay, attend it Priority Queue (Min-Heap): Day 1: heap=[2] Day 2: heap=[3] (pop 2) Day 3: heap=[4] (pop 3) Day 4: heap=[] (pop 4) FINAL RESULT Attendance Schedule: Day 1 E1 Day 2 E2 Day 3 E3 Day 1: Attend Event 1 [1,2] Day 2: Attend Event 2 [2,3] Day 3: Attend Event 3 [3,4] Output: 3 OK - All 3 events attended! No conflicts, maximum events achieved. Time: O(N log N) Key Insight: Greedy approach: Always attend the event that ends soonest among available events. Using a min-heap (priority queue) by endDay ensures we always pick the most urgent event, maximizing total attendance by avoiding future conflicts with events that could be attended later. TutorialsPoint - Maximum Number of Events That Can Be Attended | Greedy with Priority Queue
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen