Smallest element with K set bits such that sum of Bitwise AND of each array element with K is maximum | Function to find the value of X such that Bitwise AND of all array elements with X is maximum ; Stores the count of set bit at each position ; Stores the resultant value of X ; Calculate the count of set bits at each position ; If the jth bit is set ; Stores the contribution of each set bit ; Store all bit and amount of contribution ; Find the total contribution ; Sort V [ ] in decreasing order of second parameter ; Choose exactly K set bits ; Print the answer ; Driver Code
function maximizeSum ( arr , n , k ) { let cnt = new Array ( 30 ) . fill ( 0 ) ; let X = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < 30 ; j ++ ) { if ( arr [ i ] & ( 1 << j ) ) cnt [ j ] ++ ; } } let v = new Array ( ) ; for ( let i = 0 ; i < 30 ; i ++ ) { let gain = cnt [ i ] * ( 1 << i ) ; v . push ( [ i , gain ] ) ; } v . sort ( ( a , b ) => { if ( a [ 1 ] != b [ 1 ] ) return b [ 1 ] - a [ 1 ] ; return a [ 0 ] - b [ 0 ] ; } ) ; for ( let i = 0 ; i < k ; i ++ ) { X |= ( 1 << v [ i ] [ 0 ] ) ; } document . write ( X ) ; } let arr = [ 3 , 4 , 5 , 1 ] ; let K = 1 ; let N = arr . length ; maximizeSum ( arr , N , K ) ;