Find triplets in an array whose AND is maximum | Javascript program to find triplet with maximum bitwise AND . ; Flag Array initially set to true for all numbers ; 2D array for bit representation of all the numbers . Initially all bits are set to 0. ; Finding bit representation of every number and storing it in bits array . ; Checking last bit of the number ; Dividing number by 2. ; maximum And number initially 0. ; Traversing the 2d binary representation . 0 th index represents 32 th bits while 32 th index represents 0 th bit . ; If cnt greater than 3 then ( 32 - i ) th bits of the number will be set . ; Setting flags of the numbers whose ith bit is not set . ; Counting the numbers whose flag are true . ; Driver code
function maxTriplet ( a , n ) { let f = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { f [ i ] = true ; } let bits = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { bits [ i ] = new Array ( 33 ) ; for ( let j = 0 ; j < 33 ; j ++ ) { bits [ i ] [ j ] = 0 ; } } for ( let i = 0 ; i < n ; ++ i ) { let num = a [ i ] ; let j = 32 ; while ( num > 0 ) { if ( num % 2 == 1 ) { bits [ i ] [ j ] = 1 ; } j -- ; num >>= 1 ; } } let ans = 0 ; for ( let i = 0 ; i <= 32 ; ++ i ) { let cnt = 0 ; for ( let j = 0 ; j < n ; ++ j ) { if ( bits [ j ] [ i ] == 1 & f [ j ] ) { cnt ++ ; } } if ( cnt >= 3 ) { ans += Math . pow ( 2 , 32 - i ) ; for ( let j = 0 ; j < n ; ++ j ) { if ( bits [ j ] [ i ] != 1 ) { f [ j ] = false ; } } } } let cnt = 0 ; for ( let i = 0 ; i < n ; ++ i ) { if ( f [ i ] ) { cnt ++ ; } } let NumberOfTriplets = ( cnt * ( cnt - 1 ) * ( cnt - 2 ) ) / 6 ; document . write ( NumberOfTriplets + " " + ans ) ; } let a = [ 4 , 11 , 10 , 15 , 26 ] ; let n = a . length ; maxTriplet ( a , n ) ;