Program to find length of longest fibonacci subsequence in Python


Suppose we have one sequence like X_1, X_2, ..., X_n is fibonacci-like if −

  • n >= 3

  • X_i + X_i+1 = X_i+2 for all i + 2 <= n

Now suppose a strictly increasing array A forming a sequence, we have to find the length of the longest fibonacci-like subsequence of A. If there is no such sequence, then return 0.

So, if the input is like A = [1,2,3,4,5,6,7,8], then the output will be 5 because there is a sequence [1,2,3,5,8] of length 5.

To solve this, we will follow these steps −

  • sA := a new set from elements of A

  • last := last element of A

  • B := a map containing each element present in A and their frequencies

  • best := 0

  • for i in size of A down to 0, do

    • a := A[i]

    • for each b in subarray of A[from index i+1 to end], do

      • c := a+b

      • if c is present in sA, then

        • B[a,b] := 1 + B[b,c]

        • best := maximum of best and B[a,b]+2

      • otherwise when c > last, then

        • come out from loop

  • return best

Example

Let us see the following implementation to get better understanding −

from collections import Counter
def solve(A):
   sA = set(A)
   last = A[-1]
   B = Counter()
   best = 0
   for i in reversed(range(len(A))):
      a = A[i]
      for b in A[i+1:]:
         c = a+b
         if c in sA:
            B[a,b] = 1 + B[b,c]
            best = max(best , B[a,b]+2)
         elif c>last:
            break
   return best

A = [1,2,3,4,5,6,7,8]
print(solve(A))

Input

[1,2,3,4,5,6,7,8]

Output

5

Updated on: 07-Oct-2021

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements