URL
https://leetcode.com/problems/count-number-of-bad-pairs/description/?envType=daily-question&envId=2025-02-09
Code
https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/challenge/202502/count_number_of_bad_pairs/main.fsx
let countBadPairs (nums: int list) : int64 =
let h =
nums
|> List.indexed
|> List.fold
(fun acc (i, n) ->
let diff = n - i
let v = Map.tryFind diff acc |> Option.defaultValue 0L
Map.add diff (v + 1L) acc)
Map.empty
let len = List.length nums
nums
|> List.indexed
|> List.fold
(fun (acc, (rest, h)) (i, n) ->
let diff = n - i
let count = Map.find diff h
acc + rest - count, (rest - 1L, Map.add diff (count - 1L) h))
(0L, (int64 len, h))
|> fst