

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximize the bitwise OR of an array in C++
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
#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] = 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[0]); 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
- Related Questions & Answers
- Maximize the median of an array in C++
- Bitwise OR (or - ) of a range in C++
- Queries for Bitwise OR in the Index Range [L, R] of the Given Array using C++
- Bitwise OR operation between the elements of BitArray in C#
- Bitwise OR of N binary strings in C++
- Maximum bitwise AND value of a pair in an array in C++
- Bitwise exclusive OR operation between the elements of BitArray in C#
- Maximize the sum of array by multiplying prefix of array with -1 in C++
- What is Bitwise OR in C++?
- Bitwise AND and OR in Arduino
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Bitwise and (or &) of a range in C++
- Rearrange an Array to Maximize i*arr[i] using C++
- Maximize Sum Of Array After K Negations in Python
- What is Bitwise OR Operator (|) in JavaScript?
Advertisements