Length of longest Fibonacci subarray formed by removing only one element | Java program to find length of the longest subarray with all fibonacci numbers ; Function to create hash table to check for Fibonacci numbers ; Insert first two fibnonacci numbers ; Summation of last two numbers ; Update the variable each time ; Function to find the longest fibonacci subarray ; Find maximum value in the array ; Creating a set containing Fibonacci numbers ; Left array is used to count number of continuous fibonacci numbers starting from left of current element ; Check if current element is a fibonacci number ; Right array is used to count number of continuous fibonacci numbers starting from right of current element ; Check if current element is a fibonacci number ; Driver code
import java . util . * ; class GFG { static final int N = 100000 ; static void createHash ( HashSet < Integer > hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } static int longestFibSubarray ( int arr [ ] , int n ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; HashSet < Integer > hash = new HashSet < Integer > ( ) ; createHash ( hash , max_val ) ; int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; int fibcount = 0 , res = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = fibcount ; if ( hash . contains ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } fibcount = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { right [ i ] = fibcount ; if ( hash . contains ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } for ( int i = 0 ; i < n ; i ++ ) res = Math . max ( res , left [ i ] + right [ i ] ) ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 8 , 5 , 7 , 3 , 5 , 7 } ; int n = arr . length ; System . out . print ( longestFibSubarray ( arr , n ) + "NEW_LINE"); } }