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
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 <bits/stdc++.h> 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[0]); 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<Integer> sForward = new Stack<Integer>(), sBackward = new Stack<Integer>(); // 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 |
9
Time Complexity: O(N)
Recommended Posts:
- Maximum of XOR of first and second maximum of all subarrays
- Maximum value of XOR among all triplets of an array
- Minimum LCM and GCD possible among all possible sub-arrays
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
- Maximum points of intersections possible among X circles and Y straight lines
- Range Query on array whose each element is XOR of index value and previous element
- Find number of subarrays with XOR value a power of 2
- Count subarrays with sum equal to its XOR value
- Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
- Find the XOR of first half and second half elements of an array
- Minimum possible travel cost among N cities
- Count subarrays where second highest lie before highest
- Largest possible value of M not exceeding N having equal Bitwise OR and XOR between them
- Queries on XOR of XORs of all subarrays
- Sum of XOR of all subarrays
- Minimum value among AND of elements of every subset of an array
- Maximum possible XOR of every element in an array with another array
- Find last element after deleting every second element in array of n integers
- Find just strictly greater element from first array for each element in second array
- Count of contiguous subarrays possible for every index by including the element at that index
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.


