Maximum OR value of a pair in an array
Last Updated :
11 Apr, 2023
Given an array arr[] of N positive elements. The task is to find the maximum bitwise OR value of a pair from the given array.
Examples:
Input: arr[] = {4, 8, 12, 16}
Output: 28
(12, 16) is the pair with the maximum bitwise OR.
12 | 16 = 28
Input: arr[] = {4, 8, 16, 2}
Output: 24
Approach: Iterate over all the possible pairs and calculate the OR value of these pairs. Finally, print the maximum of all the values.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxOR( int arr[], int n)
{
int maxVal = 0;
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++) {
maxVal = max(maxVal, arr[i] | arr[j]);
}
return maxVal;
}
int main()
{
int arr[] = { 4, 8, 12, 16 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maxOR(arr, n);
return 0;
}
|
Java
class GFG {
static int maxOR( int arr[], int n)
{
int maxVal = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
for ( int j = i + 1 ; j < n; j++) {
maxVal = Math.max(maxVal, arr[i] | arr[j]);
}
return maxVal;
}
public static void main(String[] args)
{
int arr[] = { 4 , 8 , 12 , 16 };
int n = arr.length;
System.out.println(maxOR(arr, n));
}
}
|
Python3
def maxOR(arr, n):
maxVal = 0 ;
for i in range (n - 1 ):
for j in range (i + 1 , n):
maxVal = max (maxVal, arr[i] | arr[j]);
return maxVal;
if __name__ = = '__main__' :
arr = [ 4 , 8 , 12 , 16 ];
n = len (arr);
print (maxOR(arr, n));
|
C#
using System;
class GFG {
static int maxOR( int [] arr, int n)
{
int maxVal = 0;
for ( int i = 0; i < n - 1; i++)
for ( int j = i + 1; j < n; j++) {
maxVal = Math.Max(maxVal, arr[i] | arr[j]);
}
return maxVal;
}
static public void Main()
{
int [] arr = { 4, 8, 12, 16 };
int n = arr.Length;
Console.Write(maxOR(arr, n));
}
}
|
Javascript
<script>
function maxOR(arr, n)
{
let maxVal = 0;
for (let i = 0; i < n - 1; i++)
for (let j = i + 1; j < n; j++) {
maxVal = Math.max(maxVal, arr[i] | arr[j]);
}
return maxVal;
}
let arr = [ 4, 8, 12, 16 ];
let n = arr.length;
document.write(maxOR(arr, n));
</script>
|
Time Complexity: O(n*n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...