LeetCode 1942. The Number of the Smallest Unoccupied Chair in F#

URL

The Number of the Smallest Unoccupied Chair - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202410/the_number_of_the_smallest_unoccupied_chair/main.fsx

#r "nuget:FSharpx.Collections"

open FSharpx.Collections

let smallestChair (times: (int * int) list) (targetFriend: int) : int =
    let rec smallestChair' data q seats =
        match data with
        | [] -> Map.find targetFriend seats
        | (_, isComing, friend) :: t ->
            if isComing = -1 then
                let seat = Map.find friend seats
                smallestChair' t (PriorityQueue.insert seat q) seats
            else
                let seat, q' = PriorityQueue.pop q
                smallestChair' t q' (Map.add friend seat seats)

    let data =
        times
        |> List.indexed
        |> List.fold (fun acc (i, (come, leave)) -> (leave, -1, i) :: (come, 1, i) :: acc) []
        |> List.sort

    let len = List.length times

    let q =
        seq { 0 .. (len - 1) }
        |> Seq.fold (fun acc i -> PriorityQueue.insert i acc) (PriorityQueue.empty false)

    smallestChair' data q Map.empty