- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

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 −

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))

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

6

- Related Questions & Answers
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Length of Longest Fibonacci Subsequence in C++
- Program to find length of longest sign alternating subsequence from a list of numbers in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest common subsequence in C++
- Program to find length of longest bitonic subsequence in C++
- Program to find length of longest interval from a list of intervals in Python
- Program to find length of longest common subsequence of three strings in Python
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest valid parenthesis from given string in Python

Advertisements