Two Best Non-Overlapping Events - Problem

You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei.

You can choose at most two non-overlapping events to attend such that the sum of their values is maximized.

Return this maximum sum.

Note: The start time and end time is inclusive. You cannot attend two events where one starts and the other ends at the same time. If you attend an event with end time t, the next event must start at or after t + 1.

Input & Output

Example 1 — Basic Case
$ Input: events = [[1,3,2],[4,5,2],[2,4,3],[1,5,5]]
Output: 5
💡 Note: We can choose events [1,5,5] alone for value 5, or [1,3,2] and [4,5,2] for value 4. The maximum is 5.
Example 2 — Two Non-overlapping
$ Input: events = [[1,3,2],[4,5,2],[1,5,5]]
Output: 5
💡 Note: Either choose [1,5,5] alone for value 5, or [1,3,2] and [4,5,2] for value 4. Maximum is 5.
Example 3 — Clear Two Best
$ Input: events = [[1,5,3],[1,5,1],[6,6,5]]
Output: 8
💡 Note: Choose [1,5,3] and [6,6,5] since they don't overlap: 3 + 5 = 8.

Constraints

  • 2 ≤ events.length ≤ 105
  • events[i].length == 3
  • 1 ≤ starti ≤ endi ≤ 109
  • 1 ≤ valuei ≤ 106

Visualization

Tap to expand
Two Best Non-Overlapping Events ProblemEvents:[1,3,2][4,5,2][2,4,3][1,5,5]start=1, end=3start=4, end=5start=2, end=4start=1, end=5Time12345Event 1Event 2Event 3Event 4Options: Single event [1,5,5] = 5, or pair [1,3,2] + [4,5,2] = 4Maximum Sum: 5Choose the single highest-value event
Understanding the Visualization
1
Input Events
List of events with start time, end time, and value
2
Find Compatible
Identify which events can be paired without overlap
3
Maximize Sum
Choose best single event or pair that gives maximum total value
Key Takeaway
🎯 Key Insight: Sort events by end time and use binary search to efficiently find compatible event pairs
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.0K Views
Medium Frequency
~25 min Avg. Time
1.8K 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