Skip to main content

2054.js

/** ------------------------------------------------------------------------------
*
* 2054. Two Best Non-Overlapping Events
* Topics: Array, Sorting
* https://leetcode.com/problems/two-best-non-overlapping-events/?envType=daily-question&envId=2024-12-08
*
------------------------------------------------------------------------------ */
/**
* @param {number[][]} events
* @return {number}
*/
var maxTwoEvents = function (events) {
const endEvents = [...events]
endEvents.sort((a, b) => a[1] - b[1])
events.sort((a, b) => a[0] - b[0])

let previousValue = (result = currentEnd = 0)

for (let index = 0; index < events.length; index++) {
const [start, _, value] = events[index]

while (endEvents[currentEnd][1] < start) {
const endValue = endEvents[currentEnd][2]

previousValue = Math.max(endValue, previousValue)
currentEnd++
}
result = Math.max(previousValue + value, result)
}
return result
}