Problem statement

https://binarysearch.com/problems/Longest-Fibonacci-Subsequence/

Solution

Equal to Leetcode 0873 Length of Longest Fibonacci Subsequence.

Complexity

It is O(n^2) for time and space.

Code

class Solution:
    def solve(self, arr):
        set_arr = set(arr)
        
        @lru_cache(None)
        def dp(i, j):
            if j >= 2*i or j - i not in set_arr: return 2
            else: return dp(j - i, i) + 1
            
        ans = max(dp(i, j) for i, j in combinations(arr, 2))
        return ans if ans > 2 else 0