Maximum OR value of a pair in an Array | Set 2
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[] = {3, 6, 8, 16}
Output: 24
Explanation:
The pair giving maximum OR value is (8, 16)
8|16 = 24
Input: arr[] = {8, 7, 3, 12}
Output: 15
Explanation:
There are more than one pair giving us the maximum OR value.
8|7 = 15
Naive Approach: Refer to Maximum OR value of a pair in an array for the naive approach.
Efficient Approach: In this article, we will discuss an optimized solution for the given problem.
Follow the steps below to solve the problem:
- Find the largest element from the array.
- Perform Bitwise OR between the largest element and the remaining array elements one by one. This is because the arrangement of set bits in the largest element will contribute to maximum OR value possible from array elements.
- Print the maximum OR value obtained performing the above step.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxOR( int arr[], int n)
{
int max_value
= *max_element(arr,
arr + n);
int ans = 0;
for ( int i = 0; i < n; i++) {
ans = max(ans, (max_value
| arr[i]));
}
return ans;
}
int main()
{
int arr[] = { 3, 6, 8, 16 };
int n = sizeof (arr)
/ sizeof (arr[0]);
cout << maxOR(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG{
static int maxOR( int []arr, int n)
{
int max_value = Arrays.stream(arr).max().getAsInt();
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
ans = Math.max(ans, (max_value | arr[i]));
}
return ans;
}
public static void main(String[] args)
{
int arr[] = new int []{ 3 , 6 , 8 , 16 };
int n = 4 ;
System.out.print(maxOR(arr, n));
}
}
|
Python3
def maxOR(arr, n):
max_value = max (arr)
ans = 0
for i in range (n):
ans = max (ans, (max_value | arr[i]))
return ans
if __name__ = = "__main__" :
arr = [ 3 , 6 , 8 , 16 ]
n = len (arr)
print (maxOR(arr, n))
|
C#
using System;
using System.Linq;
class GFG{
static int maxOR( int []arr, int n)
{
int max_value = arr.Max();
int ans = 0;
for ( int i = 0; i < n; i++)
{
ans = Math.Max(ans, (max_value |
arr[i]));
}
return ans;
}
public static void Main(String[] args)
{
int []arr = { 3, 6, 8, 16 };
int n = 4;
Console.Write(maxOR(arr, n));
}
}
|
Javascript
<script>
function maxOR(arr, n)
{
let max_value = Math.max(...arr);
let ans = 0;
for (let i = 0; i < n; i++)
{
ans = Math.max(ans, (max_value | arr[i]));
}
return ans;
}
let arr = [ 3, 6, 8, 16 ];
let n = 4;
document.write(maxOR(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
20 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...