Minimizing array sum by applying XOR operation on all elements of the array in C++


Description

Given an array of size, N. Find an element X such that the sum of array elements should be minimum when XOR operation is performed with X and each element of an array.

If input array is:
arr [] = {8, 5, 7, 6, 9}
then minimum sum will be 30
Binary representation of array elments are:
8 : 1000
5 : 0101
7 : 0111
6 : 0101
9 : 1001
If X = 5 then after performing XOR sum will be 30:
8 ^ 5 = 13
5 ^ 5 = 0
7 ^ 5 = 2
6 ^ 5 = 3
9 ^ 5 = 12
Sum = 30 (13 + 0 + 2 + 3 + 12)

Algorithm

1. Create a bitMap of size 32 as we are using 32 bit integer.
2. Iterate over an array and for each element of an array:
   a. If 0th bit of an element is set then increment count of bitMap[0]
   b. If 1st bit of an element is set then increment count of bitMap[1] and so on.
3. Now find X by iterating over bitMap array as follows:
if bitMap[i] > n/2: then
X = X + pow(2, i);
4. Iterate over input array. Perform XOR operation with X and each element of an array
5. Calculate sum of array elements

Example

 Live Demo

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
const int MAX_SIZE = 32;
int getSum(int *arr, int n){
   int bitMap[MAX_SIZE];
   int bitLength = 0;
   int sum = 0;
   int res = 0;
   fill(bitMap, bitMap + n, 0);
   for (int i = 0; i < n; ++i) {
      int num = arr[i];
      int f = 0;
      while (num > 0) {
         int rem = num % 2;
         num = num / 2;
         if (rem == 1) {
            bitMap[f]++;
         }
         ++f;
         bitLength = max(bitLength, f);
      }
   }
   int candidate = 0;
   for (int i = 0; i < bitLength; ++i) {
      int num = pow(2, i);
      if (bitMap[i] > n / 2) {
         candidate += num;
      }
   }
   for (int i = 0; i < n; ++i) {
      sum += arr[i] ^ candidate;
   }
   return sum;
}
int main(){
   int arr[] = {8, 5, 7, 6, 9};
   cout << "Minimum sum: " << getSum(arr, SIZE(arr)) << "\n";
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Minimum sum: 30

Updated on: 23-Oct-2019

161 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements