LeetCode 1353. Maximum Number of Events That Can Be Attended
考点 | 难度 |
---|---|
Greedy | Easy |
题目
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.
You can attend an event i at any day d where startTimei <= d <= endTimei. You can only attend one event at any time d.
Return the maximum number of events you can attend.
思路
priority queue,所有events按开始日顺序加到priority queue里,从day 1开始参加end最早的events,并且把已经结束的events从queue里去掉
答案
class Solution(object):
def maxEvents(self, A):
A.sort(reverse=1)
h = []
res = d = 0
while A or h:
if not h: d = A[-1][0]
while A and A[-1][0] <= d:
heapq.heappush(h, A.pop()[1])
heapq.heappop(h)
res += 1
d += 1
while h and h[0] < d:
heapq.heappop(h)
return res