Minimizing array sum by applying XOR operation on all elements of the array | Javascript implementation of the approach ; Function to return the minimized sum ; To store the frequency of bit in every element ; Finding element X ; Taking XOR of elements and finding sum ; Driver code
const MAX = 25 ; function getMinSum ( arr , n ) { let bits_count = new Array ( MAX ) . fill ( 0 ) , max_bit = 0 , sum = 0 , ans = 0 ; for ( let d = 0 ; d < n ; d ++ ) { let e = arr [ d ] , f = 0 ; while ( e > 0 ) { let rem = e % 2 ; e = parseInt ( e / 2 ) ; if ( rem == 1 ) { bits_count [ f ] += rem ; } f ++ ; } max_bit = Math . max ( max_bit , f ) ; } for ( let d = 0 ; d < max_bit ; d ++ ) { let temp = Math . pow ( 2 , d ) ; if ( bits_count [ d ] > parseInt ( n / 2 ) ) ans = ans + temp ; } for ( let d = 0 ; d < n ; d ++ ) { arr [ d ] = arr [ d ] ^ ans ; sum = sum + arr [ d ] ; } return sum ; } let arr = [ 3 , 5 , 7 , 11 , 15 ] ; let n = arr . length ; document . write ( getMinSum ( arr , n ) ) ;