Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

When an event is considered as the later of at most two choices, only the greatest-valued event ending before it matters. Sorting by start time makes the set of eligible earlier events grow monotonically, while a heap identifies which endings have become eligible.

Approach

Sort events by start time and maintain a min-heap of earlier (end, value) records. Before scoring the current event, remove every event whose end is strictly less than its start, updating the best expired value. Combine that best value with the current event's value, update the answer, and store the current event in the heap. Starting the expired best at zero also permits choosing only one event. Equal end/start times overlap and must not be paired.

class Solution: def maxTwoEvents(self, events: List[List[int]]) -> int: h = [] max_prev = 0 res = 0 events.sort() for s, e, v in events: while h and s > h[0][0]: max_prev = max(max_prev, heapq.heappop(h)[1]) heapq.heappush(h, (e, v)) res = max(res, max_prev + v) return res

Complexity analysis

Let n = events.length. Both displayed implementations sort events by start time and maintain a min-heap of active event endings, taking O(n log n) time and O(n) auxiliary heap space.