Skip to main content
Back to problems
#2054
Medium Algorithms

Two best non overlapping events

Array Binary Search Dynamic Programming Sorting Heap (Priority Queue)
64.0% acceptance
Feb 25, 2026
1848
72
You are given a 0-indexed 2D integer array of events where events[i] = [startTimei, endTimei, valuei]. The ith event starts at startTimei and ends at endTimei, and if you attend this event, you will receive a value of valuei. 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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_two_events(mut events: Vec<Vec<i32>>) -> i32 {
    events.sort_unstable_by_key(|e| e[1]);
    let m = events.len();

    // prefix_max[i] = max value among events[0..=i]
    let mut prefix_max = vec![0i32; m];
    prefix_max[0] = events[0][2];
    for i in 1..m {
      prefix_max[i] = prefix_max[i - 1].max(events[i][2]);
    }

    let mut ans = 0i32;
    for i in 0..m {
      let start = events[i][0];
      // Find the latest event j where events[j][1] < start
      let pos = events.partition_point(|e| e[1] < start);
      let best_prev = if pos > 0 { prefix_max[pos - 1] } else { 0 };
      ans = ans.max(events[i][2] + best_prev);
    }
    ans
  }
}