text: Find length of longest Fibonacci like subsequence | C # 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 Code
code: using System ; using System . Collections . Generic ; class GFG { static int LongestFibSubseq ( int [ ] A , int n ) { SortedSet < int > S = new SortedSet < int > ( ) ; foreach ( int t in 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 != last ( S ) ) { int z = x + y ; x = y ; y = z ; maxLen = Math . Max ( maxLen , ++ length ) ; } } } return maxLen >= 3 ? maxLen : 0 ; } static int last ( SortedSet < int > S ) { int ans = 0 ; foreach ( int a in S ) ans = a ; return ans ; } public static void Main ( String [ ] args ) { int [ ] A = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = A . Length ; Console . Write ( LongestFibSubseq ( A , n ) ) ; } }