Find length of longest Fibonacci like subsequence | Java 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
import java . util . * ; public class GFG { static int LongestFibSubseq ( int A [ ] , int n ) { TreeSet < Integer > S = new TreeSet < > ( ) ; for ( int t : A ) { S . add ( t ) ; } 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 = 3 ; while ( S . contains ( y ) && ( y != S . last ( ) ) ) { int z = x + y ; x = y ; y = z ; maxLen = Math . max ( maxLen , ++ length ) ; } } } return maxLen >= 3 ? maxLen : 0 ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = A . length ; System . out . print ( LongestFibSubseq ( A , n ) ) ; } }