原题链接在这里:https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/description/
题目:
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.
Example 1:
Input: events = [[1,2],[2,3],[3,4]] Output: 3 Explanation: You can attend all the three events. One way to attend them all is as shown. Attend the first event on day 1. Attend the second event on day 2. Attend the third event on day 3.
Example 2:
Input: events= [[1,2],[2,3],[3,4],[1,2]] Output: 4
Constraints:
1 <= events.length <= 105
events[i].length == 2
1 <= startDayi <= endDayi <= 105
题解:
Sort the events based on start.
Have a minHeap to keep the end of event.
Incrementing the day from 1 to 100000, first poll the event that is endded before today d.
For all the event that starts today, add them into the minHeap.
If minHeap is not empay, greedy attend a event that is ending soon. res++, minHeap.poll().
Time Complexity: O(nlogn + d). n = events.length. d = 100000.
Space: O(n).
AC Java:
1 class Solution { 2 public int maxEvents(int[][] events) { 3 Arrays.sort(events, (a, b) -> Integer.compare(a[0], b[0])); 4 PriorityQueue<Integer> minHeap = new PriorityQueue<>(); 5 int res = 0; 6 int i = 0; 7 int n = events.length; 8 for(int d = 1; d <= 100000; d++){ 9 while(!minHeap.isEmpty() && minHeap.peek() < d){ 10 minHeap.poll(); 11 } 12 13 while(i < n && events[i][0] == d){ 14 minHeap.add(events[i++][1]); 15 } 16 17 if(!minHeap.isEmpty()){ 18 minHeap.poll(); 19 res++; 20 } 21 } 22 23 return res; 24 } 25 }
类似Meeting Rooms II.