Minimizing array sum by applying XOR operation on all elements of the array - GeeksforGeeks

27 Apr, 2021
Given an array arr[] of N integer elements, the task is to choose an element X and apply XOR operation on every element of the array with X such that the array sum is minimized. 
Input: arr[] = {3, 5, 7, 11, 15} Output: 26 Binary representation of the array elements are {0011, 0101, 0111, 1011, 1111} We take xor of every element with 7 in order to minimize the sum. 3 XOR 7 = 0100 (4) 5 XOR 7 = 0010 (2) 7 XOR 7 = 0000 (0) 11 XOR 7 = 1100 (12) 15 XOR 7 = 1000 (8) Sum = 4 + 2 + 0 + 12 + 8 = 26Input: arr[] = {1, 2, 3, 4, 5} Output: 14  
 
Approach: The task is to find the element X with which we have to take xor of each element.  
Convert each number into binary form and update the frequency of bit (0 or 1) in an array corresponding to the position of each bit in the element in the array.
Now, Traverse the array and check whether the element at index is more than n/2 (for ‘n’ elements, we check whether the set bit appears more than n/2 at index), and subsequently, we obtain element ‘X’
Now, take xor of ‘X’ with all the elements and return the sum.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int MAX = 25; // Function to return the minimized sumint getMinSum(int arr[], int n){    int bits_count[MAX], max_bit = 0, sum = 0, ans = 0;     memset(bits_count, 0, sizeof(bits_count));     // To store the frequency    // of bit in every element    for (int d = 0; d < n; d++) {        int e = arr[d], f = 0;        while (e > 0) {            int rem = e % 2;            e = e / 2;            if (rem == 1) {                bits_count[f] += rem;            }            f++;        }        max_bit = max(max_bit, f);    }     // Finding element X    for (int d = 0; d < max_bit; d++) {        int temp = pow(2, d);        if (bits_count[d] > n / 2)            ans = ans + temp;    }     // Taking XOR of elements and finding sum    for (int d = 0; d < n; d++) {        arr[d] = arr[d] ^ ans;        sum = sum + arr[d];    }    return sum;} // Driver codeint main(){    int arr[] = { 3, 5, 7, 11, 15 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << getMinSum(arr, n);     return 0;}
// Java implementation of the approachclass GFG {     static int MAX = 25;     // Function to return the minimized sum    static int getMinSum(int arr[], int n)    {        int bits_count[] = new int[MAX],            max_bit = 0, sum = 0, ans = 0;         // To store the frequency        // of bit in every element        for (int d = 0; d < n; d++) {            int e = arr[d], f = 0;            while (e > 0) {                int rem = e % 2;                e = e / 2;                if (rem == 1) {                    bits_count[f] += rem;                }                f++;            }            max_bit = Math.max(max_bit, f);        }         // Finding element X        for (int d = 0; d < max_bit; d++) {            int temp = (int)Math.pow(2, d);            if (bits_count[d] > n / 2)                ans = ans + temp;        }         // Taking XOR of elements and finding sum        for (int d = 0; d < n; d++) {            arr[d] = arr[d] ^ ans;            sum = sum + arr[d];        }        return sum;    }     // Driver code    public static void main(String[] args)    {        int arr[] = { 3, 5, 7, 11, 15 };        int n = arr.length;        System.out.println(getMinSum(arr, n));    }} // This code has been contributed by 29AjayKumar
# Python3 implementation of the approach MAX = 25; # Function to return the minimized sumdef getMinSum(arr, n) :    bits_count = [0]* MAX    max_bit = 0; sum = 0; ans = 0;     # To store the frequency    # of bit in every element    for d in range(n) :        e = arr[d]; f = 0;        while (e > 0) :            rem = e % 2;            e = e // 2;            if (rem == 1) :                bits_count[f] += rem;                             f += 1                     max_bit = max(max_bit, f);          # Finding element X    for d in range(max_bit) :        temp = pow(2, d);                 if (bits_count[d] > n // 2) :            ans = ans + temp;      # Taking XOR of elements and finding sum    for d in range(n) :        arr[d] = arr[d] ^ ans;        sum = sum + arr[d];         return sum      # Driver codeif __name__ == "__main__" :     arr = [ 3, 5, 7, 11, 15 ];    n = len(arr);     print(getMinSum(arr, n)) # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG {     static int MAX = 25;     // Function to return the minimized sum    static int getMinSum(int[] arr, int n)    {        int[] bits_count = new int[MAX];        int max_bit = 0, sum = 0, ans = 0;         // To store the frequency        // of bit in every element        for (int d = 0; d < n; d++) {            int e = arr[d], f = 0;            while (e > 0) {                int rem = e % 2;                e = e / 2;                if (rem == 1) {                    bits_count[f] += rem;                }                f++;            }            max_bit = Math.Max(max_bit, f);        }         // Finding element X        for (int d = 0; d < max_bit; d++) {            int temp = (int)Math.Pow(2, d);            if (bits_count[d] > n / 2)                ans = ans + temp;        }         // Taking XOR of elements and finding sum        for (int d = 0; d < n; d++) {            arr[d] = arr[d] ^ ans;            sum = sum + arr[d];        }        return sum;    }     // Driver code    public static void Main(String[] args)    {        int[] arr = { 3, 5, 7, 11, 15 };        int n = arr.Length;        Console.WriteLine(getMinSum(arr, n));    }} /* This code contributed by PrinciRaj1992 */
<script>// Javascript implementation of the approach const MAX = 25; // Function to return the minimized sumfunction getMinSum(arr, n){    let bits_count = new Array(MAX).fill(0),    max_bit = 0, sum = 0, ans = 0;     // To store the frequency    // of bit in every element    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);    }     // Finding element X    for (let d = 0; d < max_bit; d++) {        let temp = Math.pow(2, d);        if (bits_count[d] > parseInt(n / 2))            ans = ans + temp;    }     // Taking XOR of elements and finding sum    for (let d = 0; d < n; d++) {        arr[d] = arr[d] ^ ans;        sum = sum + arr[d];    }    return sum;} // Driver code    let arr = [ 3, 5, 7, 11, 15 ];    let n = arr.length;     document.write(getMinSum(arr, n)); </script>
26
 
ankthon
29AjayKumar
princiraj1992
subhammahato348
binary-representation
Bitwise-XOR
Algorithms
Arrays
Greedy
Arrays
Greedy
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray