Two Best Non-Overlapping Events - Problem

Imagine you're a time management consultant helping someone maximize their value from attending events. You have a list of events, each with a start time, end time, and value they'll gain by attending.

Your goal is to select at most two non-overlapping events that maximize the total value. Events are considered overlapping if one starts before or when another ends - there must be at least a 1-unit gap between events.

Input: A 2D array events where events[i] = [startTime, endTime, value]

Output: The maximum sum of values from selecting up to 2 non-overlapping events

Example: If you have events [[1,3,2], [4,5,2], [2,4,3]], you could pick events 1 and 2 for a total value of 4, since event 1 ends at time 3 and event 2 starts at time 4.

Input & Output

example_1.py โ€” Basic Case
$ Input: events = [[1,3,2],[4,5,2],[2,4,3]]
โ€บ Output: 4
๐Ÿ’ก Note: We can choose events [1,3,2] and [4,5,2]. Event 1 ends at time 3, and event 2 starts at time 4, so they don't overlap. Total value = 2 + 2 = 4.
example_2.py โ€” Overlapping Events
$ Input: events = [[1,3,2],[4,5,2],[1,5,5]]
โ€บ Output: 5
๐Ÿ’ก Note: The optimal choice is to attend only the event [1,5,5] which gives value 5. Although we could attend [1,3,2] and [4,5,2] for value 4, the single event [1,5,5] is better.
example_3.py โ€” Single Event
$ Input: events = [[1,5,3]]
โ€บ Output: 3
๐Ÿ’ก Note: There's only one event, so we attend it and get value 3.

Constraints

  • 2 โ‰ค events.length โ‰ค 105
  • events[i].length == 3
  • 1 โ‰ค startTimei โ‰ค endTimei โ‰ค 109
  • 1 โ‰ค valuei โ‰ค 106
  • You can attend at most 2 events

Visualization

Tap to expand
Timeline[1,3,2][2,4,3][4,5,2]ends at 3ends at 4ends at 5Binary Search Process:For event [4,5,2] starting at time 4:Search for events ending before time 4Found: [1,3,2] with value 2Result: 2 + 2 = 4
Understanding the Visualization
1
Timeline Setup
Place all events on a timeline ordered by their end times
2
Value Tracking
Keep track of the maximum value achievable up to each point
3
Binary Search
For each event, quickly find the best compatible previous event
4
Optimal Combination
Combine current event with the best previous event found
Key Takeaway
๐ŸŽฏ Key Insight: Sorting by end time + binary search allows us to efficiently find compatible events in O(n log n) time instead of O(nยฒ)
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~25 min Avg. Time
856 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