Skip to content
LC-0873 Medium LeetCode

873. Length of Longest Fibonacci Subsequence

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 58% Topics: Array, Hash Table, Dynamic Programming
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n^2)
# Space: O(n)

class Solution(object):
    def lenLongestFibSubseq(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        lookup = set(A)
        result = 2
        for i in xrange(len(A)):
            for j in xrange(i+1, len(A)):
                x, y, l = A[i], A[j], 2
                while x+y in lookup:
                    x, y, l = y, x+y, l+1
                result = max(result, l)
        return result if result > 2 else 0

Solution from kamyu104/LeetCode-Solutions · MIT

Similar questions