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

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 

Example

Let us see the following implementation to get better understanding −

#include 
using namespace std;

long solve(int k, vector 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  A = { 1, 6, 3 };
   cout 

Input

7, { 1, 6, 3 }

Output

14
Updated on: 2022-03-03T06:03:28+05:30

199 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements