Longest sub | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LucasSequence ( int arr [ ] , int n ) { int max = * max_element ( arr , arr + n ) ; unordered_set < int > s ; int a = 2 , b = 1 , c ; s . insert ( a ) ; s . insert ( b ) ; while ( b < max ) { int c = a + b ; a = b ; b = c ; s . insert ( b ) ; } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { auto it = s . find ( arr [ i ] ) ; if ( it != s . end ( ) ) count ++ ; } return count ; } int main ( ) { int arr [ ] = { 7 , 11 , 22 , 4 , 2 , 1 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << LucasSequence ( arr , n ) ; return 0 ; }