text: Find length of longest Fibonacci like subsequence | CPP implementation of above approach ; Function to return the max Length of Fibonacci subsequence ; Store all array elements in a hash table ; check until next fib element is found ; next element of fib subseq ; Driver program
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestFibSubseq ( int A [ ] , int n ) { unordered_set < int > S ( A , A + n ) ; int maxLen = 0 , x , y ; for ( int i = 0 ; i < n ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { x = A [ j ] ; y = A [ i ] + A [ j ] ; int length = 2 ; while ( S . find ( y ) != S . end ( ) ) { int z = x + y ; x = y ; y = z ; maxLen = max ( maxLen , ++ length ) ; } } } return maxLen >= 3 ? maxLen : 0 ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << LongestFibSubseq ( A , n ) ; return 0 ; }