Problem
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.
Examples
Example 1:
gantt
title Jobs
dateFormat X
axisFormat %s
section Event 0
value = 2 : 0, 3
section Event 1
value = 2 : 3, 5
section Event 2
value = 3 : done, 1, 4
| |
Example 2:
gantt
title Jobs
dateFormat X
axisFormat %s
section Event 0
value = 2 : done, 0, 3
section Event 1
value = 2 : done, 3, 5
section Event 2
value = 5 : 0, 5
| |
Example 3:
gantt
title Jobs
dateFormat X
axisFormat %s
section Event 0
value = 3 : 0, 5
section Event 1
value = 1 : 0, 5
section Event 2
value = 5 : 5, 6
| |
Solution
Method 1 - Sorting + DP + Binary Search
Here is the approach:
- Sort Events:
- First, sort the events based on their end times to facilitate the use of binary search for finding non-overlapping events.
- Dynamic Programming:
- Use a
dparray wheredp[i]represents the maximum value obtainable by considering events up to thei-thevent. - Use an auxiliary array
max_valueto keep track of the maximum value obtainable considering only one event up toi.
- Use a
- Binary Search:
- To quickly find the latest event that does not overlap with the current event, use binary search.
- Calculate Maximum Value:
- Iterate through events and for each event, use the
dpandmax_valuearrays to decide the best outcome by either including the current event alone or including it with a previously non-overlapping event.
- Iterate through events and for each event, use the
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n log n)- Sorting the events:
O(n log n) - Processing each event with binary search:
O(n log n)
- Sorting the events:
- 🧺 Space complexity:
O(n)for thedpandmax_valuearrays.