Maximum XOR value of maximum and second maximum element among all possible subarrays | Function to return the maximum possible xor ; To store the readonly answer ; Borward traversal ; Backward traversal ; Driver code
function maximumXor ( arr , n ) { let sForward = [ ] ; let sBackward = [ ] ; let ans = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { 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 ) ; 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 ) ) ;