1353. Maximum Number of Events That Can Be Attended #1898
-
Topics: You are given an array of You can attend an event Return the maximum number of events you can attend. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine the maximum number of events that can be attended given that each event has a start and end day, and only one event can be attended per day. The solution involves a greedy approach combined with a min-heap (priority queue) to efficiently manage the events that can be attended on each day. Approach
This approach ensures that we always attend the event that ends the soonest, maximizing the number of events we can attend by leaving more days available for future events. Let's implement this solution in PHP: 1353. Maximum Number of Events That Can Be Attended <?php
/**
* @param Integer[][] $events
* @return Integer
*/
function maxEvents($events) {
sort($events);
$heap = new SplMinHeap();
$i = 0;
$n = count($events);
$day = 0;
$count = 0;
while ($i < $n || !$heap->isEmpty()) {
if ($heap->isEmpty()) {
$day = $events[$i][0];
}
while ($i < $n && $events[$i][0] <= $day) {
$heap->insert($events[$i][1]);
$i++;
}
while (!$heap->isEmpty() && $heap->top() < $day) {
$heap->extract();
}
if (!$heap->isEmpty()) {
$heap->extract();
$count++;
$day++;
}
}
return $count;
}
// Test cases
// Example 1
$events = [[1,2],[2,3],[3,4]];
echo maxEvents($events); // Output: 3
// Example 2
$events = [[1,2],[2,3],[3,4],[1,2]];
echo "\n" . maxEvents($events); // Output: 4
?> Explanation:
This approach efficiently processes events by leveraging sorting and a min-heap to maximize event attendance with optimal time complexity of O(n log n), where n is the number of events. The space complexity is O(n) for storing events in the heap. |
Beta Was this translation helpful? Give feedback.
We need to determine the maximum number of events that can be attended given that each event has a start and end day, and only one event can be attended per day. The solution involves a greedy approach combined with a min-heap (priority queue) to efficiently manage the events that can be attended on each day.
Approach