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 <= n

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] < A[j] and m has (A[i] – A[j]), then

        • 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

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int lenLongestFibSubseq(vector<int> & A) {
      int ret = 0;
      unordered_map <int, int> m;
      int n = A.size();
      vector < vector <int> > dp(n, vector <int>(n));
      for(int i = 0; i < n; i++){
         m[A[i]] = i;
         for(int j = i - 1; j >= 0; j--){
            int req = A[i] - A[j];
            if(A[i] - A[j] < A[j] && m.count(A[i] - A[j])){
               dp[i][j] = max(dp[i][j], dp[j][m[A[i] - A[j]]] + 1);
            }else{
               dp[i][j] = max(dp[i][j], 2);
            }
            ret = max(ret, dp[i][j]);
         }
      }
      return ret >= 3 ? ret : 0;
   }
};
main(){
   vector<int> v = {1,2,3,4,5,6,7,8};
   Solution ob;
   cout << (ob.lenLongestFibSubseq(v));
}

Input

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

Output

5

Updated on: 30-Apr-2020

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements