Find triplets in an array whose AND is maximum | C # 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
using System ; class GFG { static void maxTriplet ( int [ ] a , int n ) { Boolean [ ] f = new Boolean [ n ] ; for ( int i = 0 ; i < n ; ++ i ) f [ i ] = true ; int [ , ] bits = new int [ n , 33 ] ; for ( int i = 0 ; i < n ; ++ i ) { int num = a [ i ] ; int j = 32 ; while ( num > 0 ) { if ( num % 2 == 1 ) { bits [ i , j ] = 1 ; } j -- ; num >>= 1 ; } } long ans = 0 ; int cnt ; for ( int i = 0 ; i <= 32 ; ++ i ) { cnt = 0 ; for ( int j = 0 ; j < n ; ++ j ) { if ( bits [ j , i ] == 1 & f [ j ] ) { cnt ++ ; } } if ( cnt >= 3 ) { ans += ( long ) Math . Pow ( 2 , 32 - i ) ; for ( int j = 0 ; j < n ; ++ j ) { if ( bits [ j , i ] != 1 ) { f [ j ] = false ; } } } } cnt = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( f [ i ] ) { cnt ++ ; } } long NumberOfTriplets = ( cnt * ( cnt - 1 ) * ( cnt - 2 ) ) / 6 ; Console . Write ( NumberOfTriplets + " ▁ " + ans ) ; } public static void Main ( String [ ] args ) { int [ ] a = { 4 , 11 , 10 , 15 , 26 } ; int n = a . Length ; maxTriplet ( a , n ) ; } }