LeetCode 1353. Maximum Number of Events That Can Be Attended

Question

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. Notice that you can only attend one event at any time d.

Return the maximum number of events you can attend.

Example

1
2
3
4
5
6
7
8
9
10
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.

Input: events = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],[1,7]]
Output: 7

Solution

Events should be sorted by end time. We need solve the earlier end event.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// time:O(n^2) space:O(~1)
public int maxEvents(int[][] events) {
if (events == null || events.length == 0 || events[0] == null || events.length == 0) {
return 0;
}
Arrays.sort(events, (a, b) -> (a[1] - b[1] != 0 ? a[1] - b[1] : a[0] - b[0]));
int res = 0;
boolean[] attend = new boolean[100001];
for (int[] event : events) {
for (int i = event[0]; i <= event[1]; i++) {
if (!attend[i]) {
attend[i] = true;
res++;
break;
}
}
}
return res;
}

// time:O(nlogn)
public int maxEvents2(int[][] events) {
if (events == null || events.length == 0 || events[0] == null || events.length == 0) {
return 0;
}

PriorityQueue<Integer> pq = new PriorityQueue<>();
Arrays.sort(events, (a, b) -> Integer.compare(a[0], b[0]));
int index = 0, res = 0, n = events.length;
for (int d = 1; d <= 100000; d++) {
while (index < n && events[index][0] == d)
pq.offer(events[index++][1]); // 加入这个的结束时间。
while (pq.size() > 0 && pq.peek() < d)
pq.poll();
if (pq.size() > 0) {
res++;
pq.poll();
}
}
return res;
}