Two Best Non-Overlapping Events (LeetCode 2054): Solution and Explanation

Medium
Array
Binary search
Dynamic programming
Sorting
Heap (priority queue)

Pick at most two events that do not overlap (times are inclusive) to maximize the sum of their values.

Intuition

Any valid pair has an earlier event and a later event, and the earlier one ends strictly before the later one starts. So fix the later event: its best partner is the single most valuable event that ended before its start time.

If you visit events in order of start time, the set of events that ended before the current start can only grow, because the start time only moves forward. That means you never need to remove anything; a running maximum is enough.

To grow that set efficiently, keep a second copy of the events sorted by end time and a pointer into it. Before handling an event, move the pointer past every event whose end is less than the current start, updating the running maximum best_before.

The candidate for the current event is best_before + value. When nothing has finished yet, best_before is 0, which covers the choice of attending just one event.

Approach: Sweep by start, pointer over end-sorted events

  1. Sort one copy of events by start time and another by end time.
  2. Set best_before = 0, ans = 0, j = 0.
  3. For each event in start order: while by_end[j] ends before this start, best_before = max(best_before, by_end[j].value) and advance j.
  4. ans = max(ans, best_before + value).
  5. Return ans.

Step-by-step example

events = [[1,3,2],[4,5,2],[2,4,3]]
  1. By start: [1,3,2], [2,4,3], [4,5,2]. By end: [1,3,2], [2,4,3], [4,5,2].
  2. Start 1: nothing ended before 1. Candidate 0 + 2 = 2, ans = 2.
  3. Start 2: nothing ended before 2. Candidate 0 + 3 = 3, ans = 3.
  4. Start 4: [1,3,2] ended at 3 < 4, best_before = 2. [2,4,3] ends at 4, which is not before 4, so it stays out. Candidate 2 + 2 = 4, ans = 4.
  5. The answer is 4.

Code: Python, Java, C++

1class Solution:
2    def maxTwoEvents(self, events: List[List[int]]) -> int:
3        by_start = sorted(events)
4        by_end = sorted(events, key=lambda e: e[1])
5        best_before = 0
6        ans = 0
7        j = 0
8        for start, end, value in by_start:
9            while j < len(by_end) and by_end[j][1] < start:
10                best_before = max(best_before, by_end[j][2])
11                j += 1
12            ans = max(ans, best_before + value)
13        return ans
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Two sorts dominate. The sweep is O(n) because the pointer j only moves forward.

Space

O(n)

The two sorted copies.

Other approaches

Min-heap of end times (time O(n log n), space O(n))

Sort by start and push (end, value) into a min-heap as you go. Before handling an event, pop every heap entry whose end is before the current start and fold its value into best_before.

Suffix maximum with binary search (time O(n log n), space O(n))

Sort by start and build a suffix maximum of values. For each event, binary search the first event starting after its end and add that suffix maximum.

Check every pair (time O(n^2), space O(1))

Try all pairs and keep the best non-overlapping sum. Simple but far too slow for 10^5 events.

Common mistakes

  • Treating touching events as compatible. Times are inclusive, so an event ending at t overlaps one starting at t; the test must be end < start, not end <= start.
  • Forgetting the single-event option. One very valuable event can beat every pair.
  • Sorting only by start and assuming earlier starts end earlier. A long event that starts first can end last, which is why the end-sorted copy is needed.

Frequently asked questions

Why can best_before only grow?

Events are visited in increasing start time, so any event that ended before an earlier start also ended before every later start. Nothing ever leaves the finished set.

Why fix the later event instead of the earlier one?

Either works. Fixing the later one lets the partner be a simple running maximum of everything already finished.

Do I need 64-bit integers?

No. Two values of at most 10^6 sum to at most 2 * 10^6.

What is the complexity?

O(n log n) time for sorting and O(n) space.