Two Best Non-Overlapping Events Problem
Description
LeetCode Problem 2054.
You are given a 0-indexed 2D integer array of events where events[i] = [startTime_i, endTime_i, value_i]. The i^th event starts at startTime_iand ends at endTime_i, and if you attend this event, you will receive a value of value_i. 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 that the start time and end time is inclusive: that is, you cannot attend two events where one of them starts and the other ends at the same time. More specifically, if you attend an event with end time t, the next event must start at or after t + 1.
Example 1:

Input: events = [[1,3,2],[4,5,2],[2,4,3]]
Output: 4
Explanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.
Example 2:

Input: events = [[1,3,2],[4,5,2],[1,5,5]]
Output: 5
Explanation: Choose event 2 for a sum of 5.
Example 3:

Input: events = [[1,5,3],[1,5,1],[6,6,5]]
Output: 8
Explanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.
Constraints:
2 <= events.length <= 10^5events[i].length == 31 <= startTime_i <= endTime_i <= 10^91 <= value_i <= 10^6
Solution
Approach: Sorting + Binary Search
Sort the events by start time and precompute f[i], the best value of a single event chosen among events i to the end (a suffix maximum).
Then treat each event as the first one of the pair. Binary search for the first event whose start time is greater than the current event's end time, at index idx. The best partner is worth f[idx] (or 0 if idx is past the end), so this event gives value + f[idx]. The answer is the maximum over all events; picking a single event is covered because the partner value can be 0.
Complexity: time O(n log n), space O(n), where n is the number of events.
from bisect import bisect_right
class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
events.sort()
n = len(events)
starts = [e[0] for e in events]
f = [events[-1][2]] * n
for i in range(n - 2, -1, -1):
f[i] = max(f[i + 1], events[i][2])
ans = 0
for _, e, v in events:
idx = bisect_right(starts, e)
if idx < n:
v += f[idx]
ans = max(ans, v)
return ans