Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIMaximum XOR value of maximum and second maximum element among all possible...

Maximum XOR value of maximum and second maximum element among all possible subarrays

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:
{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:
 

 

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++) {
 
        // forward 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++)
    {
 
        // forward 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):
 
        # forward 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++)
    {
 
        // forward 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


Javascript




<script>
    // Javascript implementation of the approach
     
    // Function to return the maximum possible xor
    function maximumXor(arr, n)
    {
        let sForward = [];
          let sBackward = [];
 
        // To store the readonly answer
        let ans = -1;
 
        for (let i = 0; i < n; i++)
        {
 
            // forward traversal
            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);
 
            // Backward traversal
            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));
     
    // This code is contributed by rameshtravel07.
</script>


Output: 

9

 

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. 
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments