Maximum value of XOR among all triplets of an array in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of integers, the task is to find the maximum XOR value of any triplet pair among all the possible triplet pairs. Note that an array element can be used more than once.

If given input array is {0, 4, 6, 5} then maximum value of triplet is {4, 6, 5} = 7.

Algorithm

1. Store all possible values of XOR between all possible twoelement pairs from the array in a set
2. C++ STL Set data structure is used to avoid the repetitions of XOR values
3. XOR between every set element and array element to get the maximum value for any triplet pair

Example

#include <bits/stdc++.h>
using namespace std;
void getMaxXORTripplet(int *arr, int n){
   set<int> s;
   for (int i = 0; i < n; ++i) {
      for (int j = i; j < n; ++j) {
         s.insert(arr[i] ^ arr[j]);
      }
   }
   int ans = 0;
   for (auto i : s) {
      for (int j = 0; j < n; ++j) {
         ans = max(ans, i ^ arr[j]);
      }
   }
   cout << "Result = " << ans << "\n";
}
int main(){
   int arr[] = {0, 4, 6, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   getMaxXORTripplet(arr, n);
   return 0;
}

Output

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

Result = 7
raja
Published on 10-Feb-2020 09:41:38
Advertisements