# 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

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

Naive Approach: Generate all possible subarrays with length greater than 1 and for each possible subarrays find the XOR value of first and second maximum element of the subarray and find out the maximum value out of them.

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] –
1. 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].
2. Push arr[i] into the stack.
3. 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++

 `// C++ implmentation of the above approach. ` ` `  `#include ` ` `  `using` `namespace` `std; ` ` `  `// Function to find the maximum XOR value ` `int` `findMaxXOR(vector<``int``> arr, ``int` `n){ ` `     `  `    ``vector<``int``> stack; ` `    ``int` `res = 0, l = 0, i; ` ` `  `    ``// Traversing given array ` `    ``for` `(i = 0; i < n; i++) { ` ` `  `        ``// If there are elements in stack ` `        ``// and top of stack is less than ` `        ``// current element then pop the elements ` `        ``while` `(!stack.empty() && ` `                ``stack.back() < arr[i]) { ` `            ``stack.pop_back(); ` `            ``l--; ` `        ``} ` ` `  `        ``// Push current element ` `        ``stack.push_back(arr[i]); ` `         `  `        ``// Increasing length of stack ` `        ``l++; ` `        ``if` `(l > 1) { ` `            ``// Updating the maximum result ` `            ``res = max(res,  ` `             ``stack[l - 1] ^ stack[l - 2]); ` `        ``} ` `    ``} ` ` `  ` `  `    ``return` `res; ` `} ` ` `  `// Driver Code ` `int` `main() ` `{ ` `    ``// Initializing array ` `    ``vector<``int``> arr{ 9, 8, 3, 5, 7 }; ` `    ``int` `result1 = findMaxXOR(arr, 5); ` `     `  `    ``// Reversing the array(vector) ` `    ``reverse(arr.begin(), arr.end()); ` `     `  `    ``int` `result2 = findMaxXOR(arr, 5); ` `     `  `    ``cout << max(result1, result2); ` `     `  `    ``return` `0; ` `} `

## Java

 `// Java implmentation of the above approach. ` `import` `java.util.*; ` ` `  `class` `GFG{ ` ` `  `// Function to find the maximum XOR value ` `static` `int` `findMaxXOR(Vector arr, ``int` `n){ ` `     `  `    ``Vector stack = ``new` `Vector(); ` `    ``int` `res = ``0``, l = ``0``, i; ` ` `  `    ``// Traversing given array ` `    ``for` `(i = ``0``; i < n; i++) { ` ` `  `        ``// If there are elements in stack ` `        ``// and top of stack is less than ` `        ``// current element then pop the elements ` `        ``while` `(!stack.isEmpty() && ` `                ``stack.get(stack.size()-``1``) < arr.get(i)) { ` `            ``stack.remove(stack.size()-``1``); ` `            ``l--; ` `        ``} ` ` `  `        ``// Push current element ` `        ``stack.add(arr.get(i)); ` `         `  `        ``// Increasing length of stack ` `        ``l++; ` `        ``if` `(l > ``1``) { ` `             `  `            ``// Updating the maximum result ` `            ``res = Math.max(res,  ` `            ``stack.get(l - ``1``) ^ stack.get(l - ``2``)); ` `        ``} ` `    ``} ` ` `  `    ``return` `res; ` `} ` ` `  `// Driver Code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``// Initializing array ` `    ``Integer []temp = { ``9``, ``8``, ``3``, ``5``, ``7` `}; ` `    ``Vector arr = ``new` `Vector<>(Arrays.asList(temp)); ` `    ``int` `result1 = findMaxXOR(arr, ``5``); ` `     `  `    ``// Reversing the array(vector) ` `    ``Collections.reverse(arr); ` `     `  `    ``int` `result2 = findMaxXOR(arr, ``5``); ` `     `  `    ``System.out.print(Math.max(result1, result2)); ` `} ` `} ` ` `  `// This code is contributed by sapnasingh4991 `

## Python 3

 `# Python implementation of the approach ` ` `  `from` `collections ``import` `deque ` ` `  ` `  `def` `maxXOR(arr): ` `    ``# Declaring stack ` `    ``stack ``=` `deque() ` `     `  `    ``# Initializing the length of stack ` `    ``l ``=` `0` `     `  `    ``# Initializing res1 for array ` `    ``# traversal of left to right ` `    ``res1 ``=` `0` `     `  `    ``# Traversing the array ` `    ``for` `i ``in` `arr: ` `         `  `        ``# If there are elements in stack  ` `        ``# And top of stack is less than  ` `        ``# current element then pop the stack ` `        ``while` `stack ``and` `stack[``-``1``]``1``: ` `            ``res1 ``=` `max``(res1, stack[``-``1``]^stack[``-``2``]) ` `     `  `     `  `    ``# Similar to the above method,  ` `    ``# we calculate the xor for reversed array ` `    ``res2 ``=` `0` `     `  `    ``# Clear the whole stack ` `    ``stack.clear() ` `    ``l ``=` `0` `     `  `    ``# Reversing the array ` `    ``arr.reverse() ` `    ``for` `i ``in` `arr: ` `        ``while` `stack ``and` `stack[``-``1``]``1``: ` `            ``res2 ``=` `max``(res2, stack[``-``1``]^stack[``-``2``]) ` `             `  `    ``# Printing the maximum of res1, res2 ` `    ``return` `max``(res1, res2) ` ` `  `# Driver Code ` `if` `__name__ ``=``=` `"__main__"``: ` `    ``# Initializing the array ` `    ``arr ``=` `[``9``, ``8``, ``3``, ``5``, ``7``] ` `    ``print``(maxXOR(arr)) `

## C#

 `// C# implmentation of the above approach. ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG{ ` `  `  `// Function to find the maximum XOR value ` `static` `int` `findMaxXOR(List<``int``> arr, ``int` `n){ ` `      `  `    ``List<``int``> stack = ``new` `List<``int``>(); ` `    ``int` `res = 0, l = 0, i; ` `  `  `    ``// Traversing given array ` `    ``for` `(i = 0; i < n; i++) { ` `  `  `        ``// If there are elements in stack ` `        ``// and top of stack is less than ` `        ``// current element then pop the elements ` `        ``while` `(stack.Count!=0 && ` `                ``stack[stack.Count-1] < arr[i]) { ` `            ``stack.RemoveAt(stack.Count-1); ` `            ``l--; ` `        ``} ` `  `  `        ``// Push current element ` `        ``stack.Add(arr[i]); ` `          `  `        ``// Increasing length of stack ` `        ``l++; ` `        ``if` `(l > 1) { ` `              `  `            ``// Updating the maximum result ` `            ``res = Math.Max(res,  ` `            ``stack[l - 1] ^ stack[l - 2]); ` `        ``} ` `    ``} ` `  `  `    ``return` `res; ` `} ` `  `  `// Driver Code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``// Initializing array ` `    ``int` `[]temp = { 9, 8, 3, 5, 7 }; ` `    ``List<``int``> arr = ``new` `List<``int``>(temp); ` `    ``int` `result1 = findMaxXOR(arr, 5); ` `      `  `    ``// Reversing the array(vector) ` `    ``arr.Reverse(); ` `      `  `    ``int` `result2 = findMaxXOR(arr, 5); ` `      `  `    ``Console.Write(Math.Max(result1, result2)); ` `} ` `} ` ` `  `// This code is contributed by 29AjayKumar `

Output:

```15
```

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.