Minimizing array sum by applying XOR operation on all elements of the array | Python3 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
MAX = 25 ; NEW_LINE def getMinSum ( arr , n ) : NEW_LINE INDENT bits_count = [ 0 ] * MAX NEW_LINE max_bit = 0 ; sum = 0 ; ans = 0 ; NEW_LINE for d in range ( n ) : NEW_LINE INDENT e = arr [ d ] ; f = 0 ; NEW_LINE while ( e > 0 ) : NEW_LINE INDENT rem = e % 2 ; NEW_LINE e = e // 2 ; NEW_LINE if ( rem == 1 ) : NEW_LINE INDENT bits_count [ f ] += rem ; NEW_LINE DEDENT f += 1 NEW_LINE DEDENT max_bit = max ( max_bit , f ) ; NEW_LINE DEDENT for d in range ( max_bit ) : NEW_LINE INDENT temp = pow ( 2 , d ) ; NEW_LINE if ( bits_count [ d ] > n // 2 ) : NEW_LINE INDENT ans = ans + temp ; NEW_LINE DEDENT DEDENT for d in range ( n ) : NEW_LINE INDENT arr [ d ] = arr [ d ] ^ ans ; NEW_LINE sum = sum + arr [ d ] ; NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 5 , 7 , 11 , 15 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( getMinSum ( arr , n ) ) NEW_LINE DEDENT