Home >Backend Development >PHP Tutorial >Two Best Non-Overlapping Events
2054. Two Best Non-Overlapping Events
Difficulty: Medium
Topics: Array, Binary Search, Dynamic Programming, Sorting, Heap (Priority Queue)
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.
Example 1:
Example 2:
Example 3:
Constraints:
Hint:
Solution:
We can use the following approach:
Sort Events by End Time:
Binary Search for Non-Overlapping Events:
Dynamic Programming with Max Tracking:
Iterate and Calculate the Maximum Sum:
Let's implement this solution in PHP: 2054. Two Best Non-Overlapping Events
Explanation:
Sorting:
- The events are sorted by their end time, which allows for efficient searching of the last non-overlapping event.
Binary Search:
- For each event, binary search determines the latest event that ends before the current event starts.
Max Tracking:
- We maintain an array maxUpTo, which stores the maximum value of events up to the current index. This avoids recalculating the maximum for earlier indices.
Max Sum Calculation:
- For each event, calculate the sum of its value and the best non-overlapping event's value. Update the global maximum sum accordingly.
Complexity Analysis
This solution is efficient and works well within the constraints.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Two Best Non-Overlapping Events. For more information, please follow other related articles on the PHP Chinese website!