Open In App

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

Last Updated : 25 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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. 
 



Similar Reads

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
11 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read
Maximum value of XOR among all triplets of an array
Given an array of integers 'arr', the task is to find the maximum XOR value of any triplet pair among all the possible triplet pairs. Note: An array element can be used more than once. Examples: Input: arr[] = {3, 4, 5, 6} Output: 7 The triplet with maximum XOR value is {4, 5, 6}. Input: arr[] = {1, 3, 8, 15} Output: 15 Approach: Store all possible
5 min read
Minimum LCM and GCD possible among all possible sub-arrays
Given an array arr[] of N positive integers, the task is to find the minimum LCM and GCD between elements of all possible sub-array.Examples: Input: arr[] = {4, 4, 8} Output: LCM = 4, GCD = 4 All possible sub-arrays are: {4} -&gt; LCM = 4, GCD = 4 {8} -&gt; LCM = 8, GCD = 8 {4, 8} -&gt; LCM = 8, GCD = 4Input: arr[] = {2, 66, 14, 521} Output: LCM =
6 min read
Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Minimum product of maximum and minimum element over all possible subarrays
Given an array arr[] consisting of N positive integers, the task is to find the minimum product of maximum and minimum among all possible subarrays. Examples: Input: arr[] = {6, 4, 5, 6, 2, 4}Output: 8Explanation:Consider the subarray {2, 4}, the product of minimum and maximum for this subarray is 2*4 = 8, which is minimum among all possible subarr
4 min read
Minimize difference between maximum and minimum element of all possible subarrays
Given an array arr[ ] of size N, the task is to find the minimum difference between maximum and minimum elements of all possible sized subarrays of arr[ ]. Examples: Input: arr[] = { 5, 14, 7, 10 } Output: 3Explanation: {7, 10} is the subarray having max element = 10 &amp; min element = 7, and their difference = 10 - 7 = 3 Input: arr[] = { 2, 6, 15
5 min read
Check if Array can be split into subarrays such that XOR of length of Longest Decreasing Subsequences of those subarrays is 0
Given an array of integers arr[] of size N, the task is to check whether arr[] can be split into different subarrays such that on taking the XOR of lengths of LDS (Longest decreasing subsequences) of all the subarrays is equal to 0. Print 'YES' if it is possible to split else print 'NO'. Examples: Input: arr[] = {1, 0, 3, 4, 5}Output: YESExplanatio
6 min read
Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
Given a binary-valued Undirected Graph with V vertices and E edges, the task is to find the maximum decimal equivalent among all the connected components of the graph. A binary-valued graph can be considered as having only binary numbers (0 or 1) as the vertex values. Examples: Input: E = 4, V = 7 Output: 3 Explanation: Decimal equivalents of the c
14 min read
Find maximum AND value among all K-size subsets of given Array
Given an array arr[] containing N non-negative integers, the task is to find the maximum AND value among all the subsets having length K. Examples: Input: arr[] = {1, 6, 9, 7}, K = 1Output: 9Explanation: As only one element is allowed 9 is the greatest value that can be obtained. Input: arr[] = {3, 3, 3}, K = 2Output: 3 Input: arr[] = {7, 8, 9, 10,
7 min read