Maximum XOR value of maximum and second maximum element among all possible subarrays
Last Updated :
25 May, 2022
Given an array arr[] of N distinct positive integers, let’s denote max(i, j) and secondMax(i, j) as the maximum and the second maximum element of the subarray arr[i…j]. The task is to find the maximum value of max(i, j) XOR secondMax(i, j) for all possible values of i and j. Note that the size of the subarray must be at least two.
Examples:
Input: arr[] = {1, 2, 3}
Output: 3
{1, 2}, {2, 3} and {1, 2, 3} are the only valid subarrays.
Clearly, the required XOR values are 3, 1 and 1 respectively.
Input: arr[] = {1, 8, 2}
Output: 9
Naive approach: A naive approach will be to simply iterate over all the subarrays one by one and then find the required values. This approach requires O(N3) time complexity.
Efficient approach: Let arr[i] be the second maximum element of some subarray then the maximum element can be the first element larger than arr[i] in the forward or the backward direction.
Hence, it can be shown that each element except the first and the last can act as the second maximum element at most 2 times only. Now, just calculate the next greater element of each element in the forward and the backward direction and return the maximum XOR of them. An approach to find the next greater element using stacks is described in this article.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maximumXor( int arr[], int n)
{
stack< int > sForward, sBackward;
int ans = -1;
for ( int i = 0; i < n; i++) {
while (!sForward.empty()
&& arr[i] < arr[sForward.top()]) {
ans = max(ans, arr[i] ^ arr[sForward.top()]);
sForward.pop();
}
sForward.push(i);
while (!sBackward.empty()
&& arr[n - i - 1] < arr[sBackward.top()]) {
ans = max(ans, arr[n - i - 1] ^ arr[sBackward.top()]);
sBackward.pop();
}
sBackward.push(n - i - 1);
}
return ans;
}
int main()
{
int arr[] = { 8, 1, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << maximumXor(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int maximumXor( int arr[], int n)
{
Stack<Integer> sForward = new Stack<Integer>(),
sBackward = new Stack<Integer>();
int ans = - 1 ;
for ( int i = 0 ; i < n; i++)
{
while (!sForward.isEmpty()
&& arr[i] < arr[sForward.peek()])
{
ans = Math.max(ans, arr[i] ^ arr[sForward.peek()]);
sForward.pop();
}
sForward.add(i);
while (!sBackward.isEmpty()
&& arr[n - i - 1 ] < arr[sBackward.peek()])
{
ans = Math.max(ans, arr[n - i - 1 ] ^ arr[sBackward.peek()]);
sBackward.pop();
}
sBackward.add(n - i - 1 );
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 8 , 1 , 2 };
int n = arr.length;
System.out.print(maximumXor(arr, n));
}
}
|
Python3
def maximumXor(arr: list , n: int ) - > int :
sForward, sBackward = [], []
ans = - 1
for i in range (n):
while len (sForward) > 0 and arr[i] < arr[sForward[ - 1 ]]:
ans = max (ans, arr[i] ^ arr[sForward[ - 1 ]])
sForward.pop()
sForward.append(i)
while len (sBackward) > 0 and arr[n - i - 1 ] < arr[sBackward[ - 1 ]]:
ans = max (ans, arr[n - i - 1 ] ^ arr[sBackward[ - 1 ]])
sBackward.pop()
sBackward.append(n - i - 1 )
return ans
if __name__ = = "__main__" :
arr = [ 8 , 1 , 2 ]
n = len (arr)
print (maximumXor(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int maximumXor( int []arr, int n)
{
Stack< int > sForward = new Stack< int >(),
sBackward = new Stack< int >();
int ans = -1;
for ( int i = 0; i < n; i++)
{
while (sForward.Count != 0
&& arr[i] < arr[sForward.Peek()])
{
ans = Math.Max(ans, arr[i] ^ arr[sForward.Peek()]);
sForward.Pop();
}
sForward.Push(i);
while (sBackward.Count != 0
&& arr[n - i - 1] < arr[sBackward.Peek()])
{
ans = Math.Max(ans, arr[n - i - 1] ^ arr[sBackward.Peek()]);
sBackward.Pop();
}
sBackward.Push(n - i - 1);
}
return ans;
}
public static void Main(String[] args)
{
int []arr = { 8, 1, 2 };
int n = arr.Length;
Console.Write(maximumXor(arr, n));
}
}
|
Javascript
<script>
function maximumXor(arr, n)
{
let sForward = [];
let sBackward = [];
let ans = -1;
for (let i = 0; i < n; i++)
{
while (sForward.length != 0
&& arr[i] < arr[sForward[sForward.length - 1]])
{
ans = Math.max(ans, arr[i] ^ arr[sForward[sForward.length - 1]]);
sForward.pop();
}
sForward.push(i);
while (sBackward.length != 0
&& arr[n - i - 1] < arr[sBackward[sBackward.length - 1]])
{
ans = Math.max(ans, arr[n - i - 1] ^ arr[sBackward[sBackward.length - 1]]);
sBackward.pop();
}
sBackward.push(n - i - 1);
}
return ans;
}
let arr = [ 8, 1, 2 ];
let n = arr.length;
document.write(maximumXor(arr, n));
</script>
|
Time Complexity: O(N), as we are using a loop to traverse the array and the inner while loop only transverses N times so the effective time complexity will be O(2N).
Auxiliary Space: O(N), as we are using extra space for stack.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...