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 INPUT Events Timeline: 1 2 3 4 5 E0: [1,3] v=2 E1: [4,5] v=2 E2: [2,4] v=3 E3: [1,5] v=5 events = [ [1,3,2], [4,5,2], [2,4,3], [1,5,5] ] [start, end, value] Goal: Max sum of 2 non-overlapping events ALGORITHM (DP) 1 Sort by end time Events sorted: E0,E2,E1,E3 2 Track max value seen Use prefix max for DP 3 Binary search Find non-overlapping event 4 Update max sum max(single, pair) DP Computation E3 alone: 5 (spans 1-5) E0+E1: 2+2=4 (OK pair) E2+?: overlaps all Best single: 5 Max = 5 FINAL RESULT Best Strategy: Event 3: [1,5,5] Single event wins! Comparisons: E0 + E1 = 2+2 = 4 E3 alone = 5 5 > 4 (single wins) Output: 5 OK - Maximum Sum Key Insight: Sort events by end time and use DP with binary search. For each event, find the best non-overlapping predecessor using binary search. Track prefix maximum values to get optimal pairing in O(n log n). Sometimes a single high-value event beats any pair! TutorialsPoint - Two Best Non-Overlapping Events | DP Approach
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