Length of Longest Fibonacci Subsequence LeetCode solution in Python
1class Solution(2object3): # DP. Time Complexity: O(N^2), Space Complexity: O(NlogM), M = max(A)4def lenLongestFibSubseq(self, A):5index = {Ai: i for i, Ai in enumerate(A)}6dp = collections.defaultdict(lambda: 2)7ans = 08for k, Ak in enumerate(A): # Following IJK idiom here9for j in range(k - 1, 0, -1):10i = index.get(Ak - A[j], None)11if Ak - A[j] >= A[j]:12break # Pruning for illegal Ai13if i is not None and i < j:14cur_len = dp[j, k] = dp[i, j] + 115ans = max(ans, cur_len)1617return ans # ans is either 0 or >=3 for SURE