AlgoInsight

DSA problem

Two Best Non-Overlapping Events

MediumIntervalsPattern: Intervalstop600AmazonGoogleMicrosoftBloombergApple

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_i and ends at endTime_i, and you gain a value of value_i if you attend it. You can choose at most two non-overlapping events to attend such that the sum of their values is maximized. Two events are non-overlapping when one ends strictly before the other starts — touching at a single time point still counts as overlapping. Return the maximum sum of values you can achieve.

A brute force over all pairs runs in O(n^2), too slow for the constraints. The clever observation is that, when scanning events in start-time order, for any candidate "second event" we only care about the best value among events that have already finished (endTime < currentStart). If we can maintain that "best value of finished events so far" efficiently we get an O(n log n) algorithm.

The data structure that fits perfectly is a min-heap of (endTime, value) pairs, augmented by a running variable maxFinishedValue. Walk through the events in order of increasing start time. For each event, pop every heap entry whose endTime is less than the current startTime, and as you pop each one update maxFinishedValue with its value. The answer for the current event is maxFinishedValue + currentValue (attending the current event plus the best finished one).

After processing every event, also consider attending only one event (or none) by keeping the running maximum. Push the current event's (endTime, value) into the heap before moving on. The total complexity is O(n log n) time and O(n) auxiliary space.

Examples

Example 1
Input: events = [[1,3,2],[4,5,2],[2,4,3]]
Output: 4
Explanation: Sorted by start: [[1,3,2],[2,4,3],[4,5,2]]. The best two non-overlapping events are [1,3,2] and [4,5,2] (ends 3, starts 4, 3 < 4): total = 4. The pair (1,3) and (2,4) overlaps.
Example 2
Input: events = [[1,3,2],[4,5,2],[1,5,5]]
Output: 5
Explanation: No pair of non-overlapping events beats the single event [1,5,5] with value 5, so the answer is 5.
Example 3
Input: events = [[1,5,3],[1,5,1],[6,6,5]]
Output: 8
Explanation: [1,5,3] ends at 5 and [6,6,5] starts at 6, so they are non-overlapping. Their total is 3 + 5 = 8.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayintervalsheapsortinggreedy

Browse all DSA problems