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 readonly answer ; Borward traversal ; Backward traversal ; Driver code
using System ; using System . Collections . Generic ; class GFG { static int maximumXor ( int [ ] arr , int n ) { Stack < int > sForward = new Stack < int > ( ) , sBackward = new Stack < int > ( ) ; int ans = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { while ( sForward . Count != 0 && arr [ i ] < arr [ sForward . Peek ( ) ] ) { ans = Math . Max ( ans , arr [ i ] ^ arr [ sForward . Peek ( ) ] ) ; sForward . Pop ( ) ; } sForward . Push ( i ) ; 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 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 8 , 1 , 2 } ; int n = arr . Length ; Console . Write ( maximumXor ( arr , n ) ) ; } }