2054. Two Best Non-Overlapping Events #928
-
Topics: You are given a 0-indexed 2D integer array of 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 Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use the following approach: Approach
Let's implement this solution in PHP: 2054. Two Best Non-Overlapping Events <?php
/**
* @param Integer[][] $events
* @return Integer
*/
function maxTwoEvents($events) {
// Step 1: Sort events by end time
usort($events, function ($a, $b) {
return $a[1] - $b[1]; // Sort by endTime
});
$n = count($events);
$maxSum = 0;
$maxUpTo = []; // Maximum value up to index i
$maxValueSoFar = 0;
// Step 2: Prepare a list of end times for binary search
$endTimes = array_column($events, 1);
// Step 3: Iterate through events
foreach ($events as $i => $event) {
$startTime = $event[0];
$endTime = $event[1];
$value = $event[2];
// Use binary search to find the latest non-overlapping event
$left = 0;
$right = $i - 1;
$bestIndex = -1;
while ($left <= $right) {
$mid = intval(($left + $right) / 2);
if ($endTimes[$mid] < $startTime) {
$bestIndex = $mid; // Potential candidate
$left = $mid + 1;
} else {
$right = $mid - 1;
}
}
// If a non-overlapping event is found, use its maximum value
$currentSum = $value;
if ($bestIndex != -1) {
$currentSum += $maxUpTo[$bestIndex];
}
// Update the maximum sum found so far
$maxSum = max($maxSum, $currentSum);
// Update the max value up to the current index
$maxValueSoFar = max($maxValueSoFar, $value);
$maxUpTo[$i] = $maxValueSoFar;
}
return $maxSum;
}
// Example Usage:
$events1 = [[1, 3, 2], [4, 5, 2], [2, 4, 3]];
$events2 = [[1, 3, 2], [4, 5, 2], [1, 5, 5]];
$events3 = [[1, 5, 3], [1, 5, 1], [6, 6, 5]];
echo maxTwoEvents($events1) . "\n"; // Output: 4
echo maxTwoEvents($events2) . "\n"; // Output: 5
echo maxTwoEvents($events3) . "\n"; // Output: 8
?> Explanation:
Complexity Analysis
This solution is efficient and works well within the constraints. |
Beta Was this translation helpful? Give feedback.
We can use the following approach:
Approach
Sort Events by End Time:
Binary Search for Non-Overlapping Events:
Dynamic Programming with Max Tracking:
Iterate and Calculate the Maximum Sum: