Related Articles
Maximum XOR value of maximum and second maximum element among all possible subarrays
• Last Updated : 18 Feb, 2020

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…l]. 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

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

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++

 `// C++ implementation of the approach``#include ``using` `namespace` `std;`` ` `// Function to return the maximum possible xor``int` `maximumXor(``int` `arr[], ``int` `n)``{``    ``stack<``int``> sForward, sBackward;`` ` `    ``// To store the final answer``    ``int` `ans = -1;`` ` `    ``for` `(``int` `i = 0; i < n; i++) {`` ` `        ``// Borward traversal``        ``while` `(!sForward.empty()``               ``&& arr[i] < arr[sForward.top()]) {``            ``ans = max(ans, arr[i] ^ arr[sForward.top()]);``            ``sForward.pop();``        ``}``        ``sForward.push(i);`` ` `        ``// Backward traversal``        ``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;``}`` ` `// Driver code``int` `main()``{``    ``int` `arr[] = { 8, 1, 2 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);`` ` `    ``cout << maximumXor(arr, n);`` ` `    ``return` `0;``}`

## Java

 `// Java implementation of the approach``import` `java.util.*;`` ` `class` `GFG``{`` ` `// Function to return the maximum possible xor``static` `int` `maximumXor(``int` `arr[], ``int` `n)``{``    ``Stack sForward = ``new` `Stack(),``            ``sBackward = ``new` `Stack();`` ` `    ``// To store the final answer``    ``int` `ans = -``1``;`` ` `    ``for` `(``int` `i = ``0``; i < n; i++)``    ``{`` ` `        ``// Borward traversal``        ``while` `(!sForward.isEmpty()``            ``&& arr[i] < arr[sForward.peek()]) ``        ``{``            ``ans = Math.max(ans, arr[i] ^ arr[sForward.peek()]);``            ``sForward.pop();``        ``}``        ``sForward.add(i);`` ` `        ``// Backward traversal``        ``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;``}`` ` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``8``, ``1``, ``2` `};``    ``int` `n = arr.length;`` ` `    ``System.out.print(maximumXor(arr, n));`` ` `}``}`` ` `// This code is contributed by 29AjayKumar`

## Python3

 `# Python3 implementation of the approach`` ` `# Function to return the maximum possible xor``def` `maximumXor(arr: ``list``, n: ``int``) ``-``> ``int``:``    ``sForward, sBackward ``=` `[], []`` ` `    ``# To store the final answer``    ``ans ``=` `-``1`` ` `    ``for` `i ``in` `range``(n):`` ` `        ``# Borward traversal``        ``while` `len``(sForward) > ``0` `and` `arr[i] < arr[sForward[``-``1``]]:``            ``ans ``=` `max``(ans, arr[i] ^ arr[sForward[``-``1``]])``            ``sForward.pop()`` ` `        ``sForward.append(i)`` ` `        ``# Backward traversal``        ``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`` ` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:`` ` `    ``arr ``=` `[``8``, ``1``, ``2``]``    ``n ``=` `len``(arr)``    ``print``(maximumXor(arr, n))`` ` `# This code is contributed by``# sanjeev2552`

## C#

 `// C# implementation of the approach``using` `System;``using` `System.Collections.Generic;`` ` `class` `GFG``{`` ` `// Function to return the maximum possible xor``static` `int` `maximumXor(``int` `[]arr, ``int` `n)``{``    ``Stack<``int``> sForward = ``new` `Stack<``int``>(),``            ``sBackward = ``new` `Stack<``int``>();`` ` `    ``// To store the readonly answer``    ``int` `ans = -1;`` ` `    ``for` `(``int` `i = 0; i < n; i++)``    ``{`` ` `        ``// Borward traversal``        ``while` `(sForward.Count != 0``            ``&& arr[i] < arr[sForward.Peek()]) ``        ``{``            ``ans = Math.Max(ans, arr[i] ^ arr[sForward.Peek()]);``            ``sForward.Pop();``        ``}``        ``sForward.Push(i);`` ` `        ``// Backward traversal``        ``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;``}`` ` `// Driver code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]arr = { 8, 1, 2 };``    ``int` `n = arr.Length;`` ` `    ``Console.Write(maximumXor(arr, n));`` ` `}``}`` ` `// This code is contributed by PrinciRaj1992`
Output:
```9
```

Time Complexity: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up