Open In App

Maximum of XOR of first and second maximum of all subarrays

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Brute Force Approach:

The brute force approach to solve this problem involves generating all possible subarrays of length greater than 1 and finding the XOR value of the first and second maximum elements in each subarray. Finally, we can return the maximum XOR value obtained.

  • Initialize a variable maxXOR with the minimum possible integer value.
  • Iterate over all possible pairs of indices (i, j) such that i < j.
  • For each pair (i, j), find the first and second maximum elements in the subarray arr[i..j]. To do this, initialize two variables firstMax and secondMax with the maximum and minimum of arr[i] and arr[j], respectively. Then, iterate over all indices k such that i < k < j and update the values of firstMax and secondMax as required.
  • Compute the XOR value of the first and second maximum elements in the current subarray and update the maximum XOR value obtained so far if necessary.
  • Finally, return the maximum XOR value obtained.

Below is the implementation of the above approach:

C++




// C++ implementation of the above approach.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum XOR value
int findMaxXOR(vector<int> arr, int n) {
    int maxXOR = INT_MIN;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            int firstMax = max(arr[i], arr[j]);
            int secondMax = min(arr[i], arr[j]);
            for (int k = i + 1; k < j; k++) {
                if (arr[k] > firstMax) {
                    secondMax = firstMax;
                    firstMax = arr[k];
                } else if (arr[k] > secondMax) {
                    secondMax = arr[k];
                }
            }
            maxXOR = max(maxXOR, firstMax ^ secondMax);
        }
    }
    return maxXOR;
}
 
 
// 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




import java.util.*;
public class GFG {
    // Function to find the maximum XOR value
    public static int findMaxXOR(int[] arr, int n)
    {
        int maxXOR = Integer.MIN_VALUE;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int firstMax = Math.max(arr[i], arr[j]);
                int secondMax = Math.min(arr[i], arr[j]);
                for (int k = i + 1; k < j; k++) {
                    if (arr[k] > firstMax) {
                        secondMax = firstMax;
                        firstMax = arr[k];
                    }
                    else if (arr[k] > secondMax) {
                        secondMax = arr[k];
                    }
                }
                maxXOR = Math.max(maxXOR,
                                  firstMax ^ secondMax);
            }
        }
        return maxXOR;
    }
 
    public static void main(String[] args)
    {
        // Initializing array
        int[] arr = { 9, 8, 3, 5, 7 };
        int result1 = findMaxXOR(arr, 5);
 
        // Reversing the array
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
 
        int result2 = findMaxXOR(arr, 5);
 
        System.out.println(Math.max(result1, result2));
    }
}


Python3




def find_max_xor(arr, n):
    max_xor = float('-inf')
     
    # Iterate through all pairs of elements in the array
    for i in range(n):
        for j in range(i + 1, n):
            # Find the two maximum elements in the current pair
            first_max = max(arr[i], arr[j])
            second_max = min(arr[i], arr[j])
             
            # Iterate through the remaining elements
            for k in range(i + 1, j):
                # Update the maximum and second maximum elements
                if arr[k] > first_max:
                    second_max = first_max
                    first_max = arr[k]
                elif arr[k] > second_max:
                    second_max = arr[k]
             
            # Update the maximum XOR value
            max_xor = max(max_xor, first_max ^ second_max)
     
    return max_xor
 
 
# Driver Code
if __name__ == "__main__":
    # Initializing array
    arr = [9, 8, 3, 5, 7]
    result1 = find_max_xor(arr, 5)
 
    # Reversing the array
    arr.reverse()
 
    result2 = find_max_xor(arr, 5)
 
    # Print the maximum XOR value among the two results
    print(max(result1, result2))


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Function to find the maximum XOR value
    static int FindMaxXOR(List<int> arr, int n)
    {
        int maxXOR = int.MinValue;
         
        // Iterate over all pairs of elements in the array
        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                int firstMax = Math.Max(arr[i], arr[j]);
                int secondMax = Math.Min(arr[i], arr[j]);
                 
                // Iterate between the two selected elements to find the second and third maximum values
                for (int k = i + 1; k < j; k++)
                {
                    if (arr[k] > firstMax)
                    {
                        secondMax = firstMax;
                        firstMax = arr[k];
                    }
                    else if (arr[k] > secondMax)
                    {
                        secondMax = arr[k];
                    }
                }
                 
                // Update the maximum XOR value
                maxXOR = Math.Max(maxXOR, firstMax ^ secondMax);
            }
        }
         
        return maxXOR;
    }
 
    // Driver Code
    static void Main()
    {
        // Initializing array
        List<int> arr = new List<int> { 9, 8, 3, 5, 7 };
        int result1 = FindMaxXOR(arr, 5);
 
        // Reversing the array
        arr.Reverse();
 
        int result2 = FindMaxXOR(arr, 5);
 
        // Output the maximum result
        Console.WriteLine(Math.Max(result1, result2));
    }
}


Javascript




// Function to find the maximum XOR value
function findMaxXOR(arr) {
    let maxXOR = Number.MIN_SAFE_INTEGER;
    const n = arr.length;
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            let firstMax = Math.max(arr[i], arr[j]);
            let secondMax = Math.min(arr[i], arr[j]);
            for (let k = i + 1; k < j; k++) {
                if (arr[k] > firstMax) {
                    secondMax = firstMax;
                    firstMax = arr[k];
                } else if (arr[k] > secondMax) {
                    secondMax = arr[k];
                }
            }
            maxXOR = Math.max(maxXOR, firstMax ^ secondMax);
        }
    }
    return maxXOR;
}
// Driver Code
const arr = [9, 8, 3, 5, 7];
const result1 = findMaxXOR(arr);
 
// Reversing the array(vector)
arr.reverse();
const result2 = findMaxXOR(arr);
console.log(Math.max(result1, result2));


Output

15




Time Complexity: O(n^3), where n is the length of the array.

Space Complexity: O(1) as are not using any extra space.

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++ implementation of the above approach.
 
#include <bits/stdc++.h>
 
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 implementation of the above approach.
import java.util.*;
 
class GFG{
 
// Function to find the maximum XOR value
static int findMaxXOR(Vector<Integer> arr, int n){
     
    Vector<Integer> stack = new Vector<Integer>();
    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<Integer> 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]<i:
            stack.pop()
            # Simultaneously decrease the
            # length of stack
            l-= 1
     
        # Append the current element
        stack.append(i)
        # Increase the length of stack
        l+= 1
         
        # If there are atleast two elements
        # in stack If xor of top two elements
        # is maximum, we will update the res1
        if l>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]<i:
            stack.pop()
            l-= 1
     
        stack.append(i)
        l+= 1
        if l>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# implementation 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


Javascript




<script>
// C++ implementation of the above approach.
 
// Function to find the maximum XOR value
function findMaxXOR(arr, n){
     
    let stack = new Array();
    let 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.length && stack[stack.length - 1] < arr[i]) {
            stack.pop();
            l--;
        }
 
        // Push current element
        stack.push(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
 
    // Initializing array
    let arr = [ 9, 8, 3, 5, 7 ];
    let result1 = findMaxXOR(arr, 5);
     
    // Reversing the array(vector)
    arr.reverse();
     
    let result2 = findMaxXOR(arr, 5);
     
    document.write(Math.max(result1, result2));
 
    // This code is contributed by _saurabh_jaiswal
</script>


Output

15






Time Complexity: O(n)
Auxiliary Space: O(n), where n is the length of the given array.



Similar Reads

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:
5 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
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
Find the XOR of first half and second half elements of an array
Given an array arr of size N. The task is to find the XOR of the first half (N/2) elements and second half elements (N - N/2) of an array.Examples: Input: arr[]={20, 30, 50, 10, 55, 15, 42} Output: 56, 24 Explanation: XOR of first half elements 20 ^ 30 ^ 50 is 56 Xor of second half elements 10 ^ 55 ^ 15 ^ 42 is 24Input: arr[]={50, 45, 36, 6, 8, 87}
4 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Find all unique pairs of maximum and second maximum elements over all sub-arrays in O(NlogN)
Let [Tex](a, b) [/Tex]represent the ordered pair of the second maximum and the maximum element of an array respectively. We need to find all such unique pairs overall contiguous sub-arrays of a given array. Examples: Input: Arr = [ 1, 2, 3, 4, 5 ] Output: (1, 2) (2, 3) (3, 4) (4, 5) Input: Arr = [ 1, 1, 2 ] Output: (1, 1) (1, 2) Input: Arr = [ 1, 2
13 min read
Split array into K subarrays such that sum of maximum of all subarrays is maximized
Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print "-1". Examples: Input: arr[] = {5, 3, 2, 7, 6, 4},
11 min read
Split into K subarrays to minimize the maximum sum of all subarrays
Given an Array[] of N elements and a number K. ( 1 &lt;= K &lt;= N ) . Split the given array into K subarrays (they must cover all the elements). The maximum subarray sum achievable out of K subarrays formed, must be the minimum possible. Find that possible subarray sum.Examples: Input : Array[] = {1, 2, 3, 4}, K = 3 Output : 4 Optimal Split is {1,
15 min read
Python | Largest, Smallest, Second Largest, Second Smallest in a List
Since, unlike other programming languages, Python does not have arrays, instead, it has list. Using lists is more easy and comfortable to work with in comparison to arrays. Moreover, the vast inbuilt functions of Python, make the task easier. So using these techniques, let's try to find the various ranges of the number in a given list. Examples: In
5 min read
Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays
Given an array arr[] consisting of N integers, the task is to maximize the sum of the difference of the maximum and minimum in each subarrays by splitting the given array into non-overlapping subarrays. Examples: Input: arr[] = {8, 1, 7, 9, 2}Output: 14Explanation:Split the given array arr[] as {8, 1}, {7, 9, 2}. Now, the sum of the difference maxi
7 min read