Untitled

mail@pastecode.io avatar
unknown
kotlin
2 months ago
999 B
1
Indexable
Never
class Solution {
    fun maxEvents(events: Array<IntArray>): Int {
        val N = events.size
        events.sortWith(compareBy({ it[0] }, { it[1] })) // sort by start
        var totalAttends = 1
        var currAttends = 1
        var merged = Pair(events[0][0], events[0][1])

        for (i in 1 until N) {
            val (lastStart, lastEnd) = merged
            val currStart = events[i][0] 
            val currEnd = events[i][1]

            if (currStart <= lastEnd) { // intersection
                merged = Pair(minOf(currStart, lastStart), maxOf(currEnd, lastEnd))
                val maxAttends = merged.second - merged.first + 1
                if (currAttends < maxAttends) {
                    currAttends += 1
                    totalAttends += 1
                }
            } else { // new interval
                merged = Pair(currStart, currEnd)
                currAttends = 1
                totalAttends += 1
            }
        }
        return totalAttends
    }
}
Leave a Comment