Longest subsequence with a given AND value | O ( N ) | C ++ implementation of the approach ; Function to return the required length ; To store the filtered numbers ; Filtering the numbers ; If there are no elements to check ; Find the AND of all the filtered elements ; Check if the AND is equal to m ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLen ( int * arr , int n , int m ) { vector < int > filter ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & m ) == m ) filter . push_back ( arr [ i ] ) ; if ( filter . size ( ) == 0 ) return 0 ; int c_and = filter [ 0 ] ; for ( int i = 1 ; i < filter . size ( ) ; i ++ ) c_and &= filter [ i ] ; if ( c_and == m ) return filter . size ( ) ; return 0 ; } int main ( ) { int arr [ ] = { 7 , 3 , 3 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int m = 3 ; cout << findLen ( arr , n , m ) ; return 0 ; }