Longest sub | Java implementation of the approach ; Function to return the length of the longest required sub - sequence ; Find the maximum element from the array ; Insert all lucas numbers below max to the set a and b are first two elements of the Lucas sequence ; If current element is a Lucas number , increment count ; Return the count ; Driver code
import java . util . * ; class GFG { static int LucasSequence ( int [ ] arr , int n ) { int max = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int counter = 0 ; HashSet < Integer > s = new HashSet < > ( ) ; int a = 2 , b = 1 ; s . add ( a ) ; s . add ( b ) ; while ( b < max ) { int c = a + b ; a = b ; b = c ; s . add ( b ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( s . contains ( arr [ i ] ) ) { counter ++ ; } } return counter ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 11 , 22 , 4 , 2 , 1 , 8 , 9 } ; int n = arr . length ; System . out . println ( LucasSequence ( arr , n ) ) ; } }