Maximum range length such that A [ i ] is maximum in given range for all i from [ 1 , N ] | Function to find maximum range for each i such that arr [ i ] is max in range ; Vector to store the left and right index for each i such that left [ i ] > arr [ i ] and right [ i ] > arr [ i ] ; Traverse the array ; While s . top ( ) [ 0 ] < a [ i ] remove the top element from the stack ; Modify left [ i ] ; Clear the stack ; Traverse the array to find right [ i ] for each i ; While s . top ( ) [ 0 ] < a [ i ] remove the top element from the stack ; Modify right [ i ] ; Print the value range for each i ; Given Input ; Function Call
function MaxRange ( A , n ) { let left = new Array ( n ) . fill ( 0 ) , right = new Array ( n ) . fill ( 0 ) ; let s = [ ] ; s . push ( [ Number . MAX_SAFE_INTEGER , - 1 ] ) ; for ( let i = 0 ; i < n ; i ++ ) { while ( s [ s . length - 1 ] [ 0 ] < A [ i ] ) s . pop ( ) ; left [ i ] = s [ s . length - 1 ] [ 1 ] ; s . push ( [ A [ i ] , i ] ) ; } while ( s . length ) s . pop ( ) ; s . push ( [ Number . MAX_SAFE_INTEGER , n ] ) ; for ( let i = n - 1 ; i >= 0 ; i -- ) { while ( s [ s . length - 1 ] [ 0 ] < A [ i ] ) s . pop ( ) ; right [ i ] = s [ s . length - 1 ] [ 1 ] ; s . push ( [ A [ i ] , i ] ) ; } for ( let i = 0 ; i < n ; i ++ ) { document . write ( left [ i ] + 1 + " " ) document . write ( right [ i ] - 1 + " " ) } } let arr = [ 1 , 3 , 2 ] ; let n = arr . length ; MaxRange ( arr , n ) ;