Length of longest Fibonacci subarray formed by removing only one element | Javascript 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
let N = 100000 ; function createHash ( hash , maxElement ) { let prev = 0 , curr = 1 ; hash . add ( prev ) ; hash . add ( curr ) ; while ( curr <= maxElement ) { let temp = curr + prev ; hash . add ( temp ) ; prev = curr ; curr = temp ; } } function longestFibSubarray ( arr , n ) { let max_val = Math . max ( ... arr ) ; let hash = new Set ( ) ; createHash ( hash , max_val ) ; let left = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let right = Array . from ( { length : n } , ( _ , i ) => 0 ) ; let fibcount = 0 , res = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { left [ i ] = fibcount ; if ( hash . has ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } fibcount = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { right [ i ] = fibcount ; if ( hash . has ( arr [ i ] ) ) { fibcount ++ ; } else fibcount = 0 ; } for ( let i = 0 ; i < n ; i ++ ) res = Math . max ( res , left [ i ] + right [ i ] ) ; return res ; } let arr = [ 2 , 8 , 5 , 7 , 3 , 5 , 7 ] ; let n = arr . length ; document . write ( longestFibSubarray ( arr , n ) + " " ) ;