Longest subsequence with a given AND value | O ( N ) | Java 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
import java . util . * ; class GFG { static int findLen ( int [ ] arr , int n , int m ) { Vector < Integer > filter = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & m ) == m ) filter . add ( arr [ i ] ) ; if ( filter . size ( ) == 0 ) return 0 ; int c_and = filter . get ( 0 ) ; for ( int i = 1 ; i < filter . size ( ) ; i ++ ) c_and &= filter . get ( i ) ; if ( c_and == m ) return filter . size ( ) ; return 0 ; } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 3 , 3 , 1 , 3 } ; int n = arr . length ; int m = 3 ; System . out . println ( findLen ( arr , n , m ) ) ; } }