LeetCode 1481. Least Number of Unique Integers after K Removals in F#

URL

Least Number of Unique Integers after K Removals - LeetCode

Code

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

let toFreq arr =
    let rec toFreq' arr acc =
        match arr with
        | [] -> acc
        | h :: t ->
            match Map.tryFind h acc with
            | Some(v) -> toFreq' t (Map.add h (v + 1) acc)
            | None -> toFreq' t (Map.add h 1 acc)

    toFreq' arr Map.empty

let findLeastNumOfUniqueInts (arr: int list) (k: int) =
    let rec findLeastNumOfUniqueInts' freq k =
        match freq with
        | [] -> 0
        | (_, count) :: t ->
            if count > k then
                List.length freq
            else
                findLeastNumOfUniqueInts' t (k - count)

    let freq =
        toFreq arr |> Map.toList |> List.sortWith (fun (_, v1) (_, v2) -> compare v1 v2)

    findLeastNumOfUniqueInts' freq k