Maximum XOR value of maximum and second maximum element among all possible subarrays | Java implementation of the approach ; Function to return the maximum possible xor ; To store the final answer ; Borward traversal ; Backward traversal ; Driver code
import java . util . * ; class GFG { static int maximumXor ( int arr [ ] , int n ) { Stack < Integer > sForward = new Stack < Integer > ( ) , sBackward = new Stack < Integer > ( ) ; int ans = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ! sForward . isEmpty ( ) && arr [ i ] < arr [ sForward . peek ( ) ] ) { ans = Math . max ( ans , arr [ i ] ^ arr [ sForward . peek ( ) ] ) ; sForward . pop ( ) ; } sForward . add ( i ) ; 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 1 , 2 } ; int n = arr . length ; System . out . print ( maximumXor ( arr , n ) ) ; } }