
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Fibonacci Subsequence in Python
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
- for j in range i + 1 to n, do
- if maxLen > 2, then
- return maxLen
- otherwise,
- return 0
Let us see the following implementation to get better understanding −
Example
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
Advertisements