
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
Length of Longest Fibonacci Subsequence in C++
Suppose we have a sequence X_1, X_2, ..., X_n is fibonacci-like if −
n >= 3
X_i + X_{i+1} = X_{i+2} for all i + 2
Now suppose a strictly increasing array A of positive integers forming a sequence, we have to find the length of the longest fibonacci-like subsequence of A. If one does not exist, then return 0. So if the number is like [1,2,3,4,5,6,7,8], then the output will be 5. The longest subsequence that is Fibonacci is like [1,2,3,5,8].
To solve this, we will follow these steps −
ret := 0
create a map m, n := size of array A
create a matrix called dp of size n x n
-
for i in range 0 to n – 1
m[A[i]] := i
-
for j in range i – 1, down to 0
req := A[i] – A[j]
-
when A[i] – A[j]
dp[i, j] := max of dp[i, j], dp[j, m[A[i] – A[j]]] + 1
otherwise dp[i,j] := max of dp[i, j] and 2
ret := max of ret and dp[i,j]
return ret when ret >= 3 otherwise return 0.
Let us see the following implementation to get better understanding −
Example
#includeusing namespace std; class Solution { public: int lenLongestFibSubseq(vector & A) { int ret = 0; unordered_map m; int n = A.size(); vector > dp(n, vector (n)); for(int i = 0; i = 0; j--){ int req = A[i] - A[j]; if(A[i] - A[j] = 3 ? ret : 0; } }; main(){ vector v = {1,2,3,4,5,6,7,8}; Solution ob; cout Input
[1,2,3,4,5,6,7,8]Output
5