#2054

Two Best Non-Overlapping Events

Medium
ArrayBinary SearchDynamic ProgrammingSortingHeap (Priority Queue)Dynamic ProgrammingBinary SearchSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the events by their end times and using a dynamic programming approach, we can efficiently find the best non-overlapping events. This allows us to quickly determine the maximum value of events that do not overlap with the current event.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the events based on their end times.
  2. 2Step 2: Use a dynamic programming array to store the maximum value obtainable up to each event.
  3. 3Step 3: For each event, find the last non-overlapping event using binary search and update the DP array accordingly.
solution.py16 lines
1# Full working Python code
2import bisect
3
4def maxTwoEvents(events):
5    events.sort(key=lambda x: x[1])
6    n = len(events)
7    dp = [0] * n
8    for i in range(n):
9        dp[i] = events[i][2]
10        if i > 0:
11            dp[i] = max(dp[i], dp[i-1])
12        # Find the last non-overlapping event
13        j = bisect.bisect_right(events, [events[i][0] - 1]) - 1
14        if j >= 0:
15            dp[i] = max(dp[i], events[i][2] + (dp[j] if j >= 0 else 0))
16    return max(dp)

Complexity note: The sorting step takes O(n log n), and filling the DP array takes O(n), leading to an overall time complexity of O(n log n). The space complexity is O(n) due to the DP array.

  • 1Sorting events by end time allows us to efficiently find non-overlapping events.
  • 2Using dynamic programming helps to build solutions incrementally, maximizing values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.