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 Problem: Schedule OptimizationInput: Event RangesEvent A: [1,2]Event B: [2,3]Event C: [3,4]Timeline ViewDay 1Day 2Day 3Day 4ABCOptimal ScheduleDay 1: Event ADay 2: Event BDay 3: Event CGreedy Strategy: Always pick events ending soonestResult: 3 events attended
Understanding the Visualization
1
Input Events
Array of events with [start_day, end_day] ranges
2
Apply Strategy
Use greedy approach to select optimal events
3
Count Attended
Return maximum number of events we can attend
Key Takeaway
🎯 Key Insight: Greedy approach works - always attend events ending earliest to leave maximum room for future events
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