Maximum of XOR of first and second maximum of all subarrays
Given an array arr[] of distinct elements, the task is to find the maximum of XOR value of the first and second maximum elements of every possible subarray.
Note: Length of the Array is greater than 1.
Examples:
Input: arr[] = {5, 4, 3}
Output: 7
Explanation:
All Possible subarrays with length greater than 1 and their XOR values of first and second maximum element –
XOR of First and Second maximum({5, 4}) = 1
XOR of First and Second maximum({5, 4, 3}) = 1
XOR of First and Second maximum({4, 3}) = 7
Input: arr[] = {9, 8, 3, 5, 7}
Output: 15
Brute Force Approach:
The brute force approach to solve this problem involves generating all possible subarrays of length greater than 1 and finding the XOR value of the first and second maximum elements in each subarray. Finally, we can return the maximum XOR value obtained.
- Initialize a variable maxXOR with the minimum possible integer value.
- Iterate over all possible pairs of indices (i, j) such that i < j.
- For each pair (i, j), find the first and second maximum elements in the subarray arr[i..j]. To do this, initialize two variables firstMax and secondMax with the maximum and minimum of arr[i] and arr[j], respectively. Then, iterate over all indices k such that i < k < j and update the values of firstMax and secondMax as required.
- Compute the XOR value of the first and second maximum elements in the current subarray and update the maximum XOR value obtained so far if necessary.
- Finally, return the maximum XOR value obtained.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxXOR(vector< int > arr, int n) {
int maxXOR = INT_MIN;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
int firstMax = max(arr[i], arr[j]);
int secondMax = min(arr[i], arr[j]);
for ( int k = i + 1; k < j; k++) {
if (arr[k] > firstMax) {
secondMax = firstMax;
firstMax = arr[k];
} else if (arr[k] > secondMax) {
secondMax = arr[k];
}
}
maxXOR = max(maxXOR, firstMax ^ secondMax);
}
}
return maxXOR;
}
int main()
{
vector< int > arr{ 9, 8, 3, 5, 7 };
int result1 = findMaxXOR(arr, 5);
reverse(arr.begin(), arr.end());
int result2 = findMaxXOR(arr, 5);
cout << max(result1, result2);
return 0;
}
|
Java
import java.util.*;
public class GFG {
public static int findMaxXOR( int [] arr, int n)
{
int maxXOR = Integer.MIN_VALUE;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
int firstMax = Math.max(arr[i], arr[j]);
int secondMax = Math.min(arr[i], arr[j]);
for ( int k = i + 1 ; k < j; k++) {
if (arr[k] > firstMax) {
secondMax = firstMax;
firstMax = arr[k];
}
else if (arr[k] > secondMax) {
secondMax = arr[k];
}
}
maxXOR = Math.max(maxXOR,
firstMax ^ secondMax);
}
}
return maxXOR;
}
public static void main(String[] args)
{
int [] arr = { 9 , 8 , 3 , 5 , 7 };
int result1 = findMaxXOR(arr, 5 );
for ( int i = 0 ; i < arr.length / 2 ; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
int result2 = findMaxXOR(arr, 5 );
System.out.println(Math.max(result1, result2));
}
}
|
Python3
def find_max_xor(arr, n):
max_xor = float ( '-inf' )
for i in range (n):
for j in range (i + 1 , n):
first_max = max (arr[i], arr[j])
second_max = min (arr[i], arr[j])
for k in range (i + 1 , j):
if arr[k] > first_max:
second_max = first_max
first_max = arr[k]
elif arr[k] > second_max:
second_max = arr[k]
max_xor = max (max_xor, first_max ^ second_max)
return max_xor
if __name__ = = "__main__" :
arr = [ 9 , 8 , 3 , 5 , 7 ]
result1 = find_max_xor(arr, 5 )
arr.reverse()
result2 = find_max_xor(arr, 5 )
print ( max (result1, result2))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int FindMaxXOR(List< int > arr, int n)
{
int maxXOR = int .MinValue;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
int firstMax = Math.Max(arr[i], arr[j]);
int secondMax = Math.Min(arr[i], arr[j]);
for ( int k = i + 1; k < j; k++)
{
if (arr[k] > firstMax)
{
secondMax = firstMax;
firstMax = arr[k];
}
else if (arr[k] > secondMax)
{
secondMax = arr[k];
}
}
maxXOR = Math.Max(maxXOR, firstMax ^ secondMax);
}
}
return maxXOR;
}
static void Main()
{
List< int > arr = new List< int > { 9, 8, 3, 5, 7 };
int result1 = FindMaxXOR(arr, 5);
arr.Reverse();
int result2 = FindMaxXOR(arr, 5);
Console.WriteLine(Math.Max(result1, result2));
}
}
|
Javascript
function findMaxXOR(arr) {
let maxXOR = Number.MIN_SAFE_INTEGER;
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
let firstMax = Math.max(arr[i], arr[j]);
let secondMax = Math.min(arr[i], arr[j]);
for (let k = i + 1; k < j; k++) {
if (arr[k] > firstMax) {
secondMax = firstMax;
firstMax = arr[k];
} else if (arr[k] > secondMax) {
secondMax = arr[k];
}
}
maxXOR = Math.max(maxXOR, firstMax ^ secondMax);
}
}
return maxXOR;
}
const arr = [9, 8, 3, 5, 7];
const result1 = findMaxXOR(arr);
arr.reverse();
const result2 = findMaxXOR(arr);
console.log(Math.max(result1, result2));
|
Time Complexity: O(n^3), where n is the length of the array.
Space Complexity: O(1) as are not using any extra space.
Efficient Approach: For this problem maintain a stack and follow given steps –
- Traverse the given array from left to right, then for each element arr[i] –
- if top of the stack is less than arr[i] then pop the elements from the stack until top of the stack is less than arr[i].
- Push arr[i] into the stack.
- Find the XOR value of the top two elements of the stack and if the current XOR value is greater than the maximum found till then update the maximum value.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findMaxXOR(vector< int > arr, int n){
vector< int > stack;
int res = 0, l = 0, i;
for (i = 0; i < n; i++) {
while (!stack.empty() &&
stack.back() < arr[i]) {
stack.pop_back();
l--;
}
stack.push_back(arr[i]);
l++;
if (l > 1) {
res = max(res,
stack[l - 1] ^ stack[l - 2]);
}
}
return res;
}
int main()
{
vector< int > arr{ 9, 8, 3, 5, 7 };
int result1 = findMaxXOR(arr, 5);
reverse(arr.begin(), arr.end());
int result2 = findMaxXOR(arr, 5);
cout << max(result1, result2);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int findMaxXOR(Vector<Integer> arr, int n){
Vector<Integer> stack = new Vector<Integer>();
int res = 0 , l = 0 , i;
for (i = 0 ; i < n; i++) {
while (!stack.isEmpty() &&
stack.get(stack.size()- 1 ) < arr.get(i)) {
stack.remove(stack.size()- 1 );
l--;
}
stack.add(arr.get(i));
l++;
if (l > 1 ) {
res = Math.max(res,
stack.get(l - 1 ) ^ stack.get(l - 2 ));
}
}
return res;
}
public static void main(String[] args)
{
Integer []temp = { 9 , 8 , 3 , 5 , 7 };
Vector<Integer> arr = new Vector<>(Arrays.asList(temp));
int result1 = findMaxXOR(arr, 5 );
Collections.reverse(arr);
int result2 = findMaxXOR(arr, 5 );
System.out.print(Math.max(result1, result2));
}
}
|
Python 3
from collections import deque
def maxXOR(arr):
stack = deque()
l = 0
res1 = 0
for i in arr:
while stack and stack[ - 1 ]<i:
stack.pop()
l - = 1
stack.append(i)
l + = 1
if l> 1 :
res1 = max (res1, stack[ - 1 ]^stack[ - 2 ])
res2 = 0
stack.clear()
l = 0
arr.reverse()
for i in arr:
while stack and stack[ - 1 ]<i:
stack.pop()
l - = 1
stack.append(i)
l + = 1
if l> 1 :
res2 = max (res2, stack[ - 1 ]^stack[ - 2 ])
return max (res1, res2)
if __name__ = = "__main__" :
arr = [ 9 , 8 , 3 , 5 , 7 ]
print (maxXOR(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int findMaxXOR(List< int > arr, int n){
List< int > stack = new List< int >();
int res = 0, l = 0, i;
for (i = 0; i < n; i++) {
while (stack.Count!=0 &&
stack[stack.Count-1] < arr[i]) {
stack.RemoveAt(stack.Count-1);
l--;
}
stack.Add(arr[i]);
l++;
if (l > 1) {
res = Math.Max(res,
stack[l - 1] ^ stack[l - 2]);
}
}
return res;
}
public static void Main(String[] args)
{
int []temp = { 9, 8, 3, 5, 7 };
List< int > arr = new List< int >(temp);
int result1 = findMaxXOR(arr, 5);
arr.Reverse();
int result2 = findMaxXOR(arr, 5);
Console.Write(Math.Max(result1, result2));
}
}
|
Javascript
<script>
function findMaxXOR(arr, n){
let stack = new Array();
let res = 0, l = 0, i;
for (i = 0; i < n; i++) {
while (stack.length && stack[stack.length - 1] < arr[i]) {
stack.pop();
l--;
}
stack.push(arr[i]);
l++;
if (l > 1) {
res = Math.max(res,
stack[l - 1] ^ stack[l - 2]);
}
}
return res;
}
let arr = [ 9, 8, 3, 5, 7 ];
let result1 = findMaxXOR(arr, 5);
arr.reverse();
let result2 = findMaxXOR(arr, 5);
document.write(Math.max(result1, result2));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given array.
Last Updated :
30 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...