Program to find length of longest Fibonacci subsequence from a given list in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of strictly increasing positive numbers called nums. We have to find the length of the longest subsequence A (of length minimum 3) such that A[i] = A[i - 1] + A[i - 2] for all i > 1.

So, if the input is like nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], then the output will be 6, as we can pick [1, 2, 3, 5, 8, 13].

To solve this, we will follow these steps −

  • A := nums
  • n := size of A
  • maxLen := 0
  • S := a new set from A
  • for i in range 0 to n, do
    • for j in range i + 1 to n, do
      • x := A[j]
      • y := A[i] + A[j]
      • length := 2
      • while y is present in S, do
        • z := x + y
        • x := y
        • y := z
        • length := length + 1
        • maxLen := maximum of maxLen, length
  • if maxLen > 2, then
    • return maxLen
  • otherwise,
    • return 0

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      A = nums
      n = len(A)
      maxLen = 0
      S = set(A)
      for i in range(0, n):
         for j in range(i + 1, n):
            x = A[j]
            y = A[i] + A[j]
            length = 2
            while y in S:
               z = x + y
               x = y
               y = z
               length += 1
               maxLen = max(maxLen, length)
      if maxLen > 2:
         return maxLen
      else:
         return 0
ob = Solution()
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(ob.solve(nums))

Input

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Output

6
raja
Published on 19-Nov-2020 07:13:54
Advertisements