URL
https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/description/?envType=daily-question&envId=2025-02-27
Code
https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/challenge/202502/length_of_longest_fibonacci_subsequence/main.fsx
let lenLongestFibSubseq (arr: int list) : int =
let rec countLongestFib prev1 prev2 s acc =
if Set.contains (prev1 + prev2) s then
countLongestFib (prev1 + prev2) prev1 s (acc + 1)
else
acc
let rec lenLongestFibSubseq' arr s acc =
match arr with
| [] -> failwith "never reach here"
| _ :: [] -> acc
| h :: t ->
let count =
t
|> List.fold
(fun acc n ->
if Set.contains (h + n) s then
max acc (countLongestFib (h + n) n s 3)
else
acc)
0
lenLongestFibSubseq' t s (max acc count)
let s = Set.ofList arr
lenLongestFibSubseq' arr s 0