# Maximize the bitwise OR of an array in C++

C++Server Side ProgrammingProgramming

## Problem statement

Given an array of N integers. The bitwise OR of all the elements of the array has to be maximized by performing one task. The task is to multiply any element of the array at-most k times with a given integer x

If input array is {4, 3, 6, 1}, k = 2 and x = 3 then maximum value can be obtained is 55

## Algorithm

1. multiply an array element with (x^k) and do bitwise OR it with the bitwise OR of all previous elements
2. Multiply an array element with bitwise OR of all next elements
3. Return the maximum value after all iterations

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxOr(int *arr, int n, int k, int x){
int prefixSum[n + 1];
int suffixSum[n + 1];
int power = 1;
for (int i = 0; i < k; ++i) {
power = power * x;
}
prefixSum = 0;
for (int i = 0; i < n; ++i) {
prefixSum[i + 1] = prefixSum[i] | arr[i];
}
suffixSum[n] = 0;
for (int i = n - 1; i >= 0; --i) {
suffixSum[i] = suffixSum[i + 1] | arr[i];
}
int result = INT_MIN;
for (int i = 0; i < n; ++i) {
result = max(result, prefixSum[i] | (arr[i] * power) | suffixSum[i + 1]);
}
return result;
}
int main(){
int arr[] = {4, 3, 6, 1};
int n = sizeof(arr) / sizeof(arr);
int k = 2;
int x = 3;
cout << "Result = " << getMaxOr(arr, n, k, x) << endl;
return 0;
}

## Output

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

Result = 55