LeetCode 2070. Most Beautiful Item for Each Query in F#

URL

Most Beautiful Item for Each Query - LeetCode

Code

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

let maximumBeauty (items: (int * int) list) (queries: int list) : int list =
    let rec binarySearch query left right (items: (int * int)[]) acc =
        if left > right then
            acc
        else
            let mid = left + (right - left) / 2

            if fst items.[mid] <= query then
                binarySearch query (mid + 1) right items (max acc (snd items.[mid]))
            else
                binarySearch query left (mid - 1) items acc


    let items =
        items
        |> List.sortWith (fun (p1, b1) (p2, b2) -> if p1 = p2 then compare b2 b1 else compare p1 p2)

    let items =
        items
        |> List.fold
            (fun (acc, maxVal) (p, b) ->
                let maxVal = max maxVal b
                (p, maxVal) :: acc, maxVal)
            ([], 0)
        |> fst
        |> List.rev
        |> List.toArray

    queries |> List.map (fun q -> binarySearch q 0 (items.Length - 1) items 0)