C++ program to find maximum possible value of XORed sum

C++Server Side ProgrammingProgramming

Suppose we have an array A with N elements and another value K. For an integer X in range 0 to K, let f(X) = (X xor A[1]) + (X xor A[2]) + ... + (X xor A[N]). We have to find the maximum possible value of f.

So, if the input is like K = 7; A = [1, 6, 3], then the output will be 14, because f(4) = (4 XOR 1) + (4 XOR 6) + (4 XOR 3) = 5 + 2 + 7 = 14.

Steps

To solve this, we will follow these steps −

n := size of A
for initialize i := 45, when i >= 0, update (decrease i by 1), do:
   p := 2^i
   m := 0
   for initialize j := 0, when j < n, update (increase j by 1), do:
      if A[j] AND p is non-zero, then:
         (increase m by 1)
   if o + p <= k, then:
      if m < n - m, then:
         m := n - m
         o := o + p
   d := d + p * m
return d

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;

long solve(int k, vector<int> A){
   long n = A.size(), d = 0, m, p, o = 0;
   for (long i = 45; i >= 0; i--){
      p = pow(2, i);
      m = 0;
      for (int j = 0; j < n; j++){
         if (A[j] & p)
            m++;
      }
      if (o + p <= k){
         if (m < n - m){
            m = n - m;
            o += p;
         }
      }
      d += p * m;
   }
   return d;
}
int main(){
   int K = 7;
   vector<int> A = { 1, 6, 3 };
   cout << solve(K, A) << endl;
}

Input

7, { 1, 6, 3 }

Output

14
raja
Updated on 03-Mar-2022 06:03:28

Advertisements