此题解采用贪心算法和优先队列(最小堆)来解决问题。首先,将会议按照开始时间进行排序。使用一个优先队列来存储当前可以参加的会议的结束时间。对于每一天,从优先队列中选择结束时间最早的会议参加。这样做可以最大限度地留下空间为后续的会议。如果当前最早结束的会议已经不能参加(即结束时间小于当前日期),则将其从队列中移除。重复此过程,直到所有会议都被处理或参加。
时间复杂度: O(n log n)
空间复杂度: O(n)
class Solution:
def maxEvents(self, events: List[List[int]]) -> int:
# Sort events based on their start time
events.sort(key=itemgetter(0))
ans = 0 # This will hold the maximum number of events one can attend
i = 0 # Pointer to iterate over events
q = [] # Min-heap to store end times of the events
n = len(events) # Total number of events
today = -1 # Current day, initialized to an invalid value
while i < n:
# Update current day to the maximum of itself and the current event's start day
today = max(today, events[i][0])
# Add all events that start on or before 'today' to the heap
while i < n and events[i][0] <= today:
heappush(q, events[i][1])
i += 1
# Attempt to attend events until the heap is empty
while q:
# Pop the event with the earliest end day
end = heappop(q)
# If the event is still valid
if end >= today:
today += 1 # Attend the event and move to the next day
# Add new events that can now be attended
while i < n and events[i][0] <= today:
heappush(q, events[i][1])
i += 1
ans += 1 # Increment the count of attended events
return ans