LeetCode 2054. Two Best Non-Overlapping Events in F#

URL

https://leetcode.com/problems/two-best-non-overlapping-events/description/?envType=daily-question&envId=2024-12-08

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/challenge/202412/two_best_non_overlapping_events/main.fsx

#r "nuget:FSharpx.Collections"

open FSharpx.Collections

let maxTwoEvent (events: (int * int * int) list) : int =
    let rec updateMaxValue start q maxValue =
        match PriorityQueue.tryPeek q with
        | None -> q, maxValue
        | Some((end2, value2)) ->
            if start <= end2 then
                q, maxValue
            else
                let _, q = PriorityQueue.pop q
                updateMaxValue start q (max maxValue value2)

    let rec maxTwoEvent' events q maxVal acc =
        match events with
        | [] -> acc
        | (start, end_, value) :: t ->
            let q, maxVal = updateMaxValue start q maxVal
            let acc = max acc (maxVal + value)
            maxTwoEvent' t (PriorityQueue.insert (end_, value) q) maxVal acc

    maxTwoEvent' (List.sort events) (PriorityQueue.empty false) 0 0