Maximum XOR value of maximum and second maximum element among all possible subarrays | C ++ implementation of the approach ; Function to return the maximum possible xor ; To store the final answer ; Borward traversal ; Backward traversal ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumXor ( int arr [ ] , int n ) { stack < int > sForward , sBackward ; int ans = -1 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ! sForward . empty ( ) && arr [ i ] < arr [ sForward . top ( ) ] ) { ans = max ( ans , arr [ i ] ^ arr [ sForward . top ( ) ] ) ; sForward . pop ( ) ; } sForward . push ( i ) ; 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 ; } int main ( ) { int arr [ ] = { 8 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumXor ( arr , n ) ; return 0 ; }