LeetCode in Kotlin

1353. Maximum Number of Events That Can Be Attended

Medium

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:

Solution

import java.util.PriorityQueue

class Solution {
    fun maxEvents(events: Array<IntArray>): Int {
        events.sortWith { a: IntArray, b: IntArray -> a[0] - b[0] }
        var ans = 0
        var i = 0
        val pq = PriorityQueue<Int>()
        for (day in 1..100000) {
            while (i < events.size && events[i][0] == day) {
                pq.add(events[i][1])
                i++
            }
            while (pq.isNotEmpty() && pq.peek() < day) {
                pq.poll()
            }
            if (pq.isNotEmpty() && pq.peek() >= day) {
                pq.poll()
                ans++
            }
        }
        return ans
    }
}