
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- 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++
- Maximum bitwise AND value of a pair in an array in C++
- Maximize value of (arr[i] – i) – (arr[j] – j) in an array in C++
- Maximize the sum of array by multiplying prefix of array with -1 in C++
- Bitwise OR operation between the elements of BitArray in C#
- Bitwise and (or &) of a range in C++
- Bitwise OR of N binary strings in C++
- Rearrange an Array to Maximize i*arr[i] using C++
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Maximize Sum Of Array After K Negations in Python
- What is Bitwise OR in C++?
- Bitwise AND and OR in Arduino
- Bitwise exclusive OR operation between the elements of BitArray in C#

Advertisements