Maximum range length such that A [ i ] is maximum in given range for all i from [ 1 , N ] | Java program for above approach ; 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 ( ) . first < 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 ( ) . first < a [ i ] remove the top element from the stack ; Modify right [ i ] ; Print the value range for each i ; Driver Code ; Given Input ; Function Call
import java . awt . * ; import java . util . * ; class GFG { static class pair < T , V > { T first ; V second ; } static void MaxRange ( ArrayList < Integer > A , int n ) { int [ ] left = new int [ n ] ; int [ ] right = new int [ n ] ; Stack < pair < Integer , Integer > > s = new Stack < > ( ) ; pair < Integer , Integer > x = new pair < > ( ) ; x . first = Integer . MAX_VALUE ; x . second = - 1 ; s . push ( x ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( s . peek ( ) . first < A . get ( i ) ) s . pop ( ) ; left [ i ] = s . peek ( ) . second ; pair < Integer , Integer > y = new pair < > ( ) ; y . first = A . get ( i ) ; y . second = i ; s . push ( y ) ; } while ( ! s . empty ( ) ) s . pop ( ) ; pair < Integer , Integer > k = new pair < > ( ) ; k . first = Integer . MAX_VALUE ; k . second = n ; s . push ( k ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( s . peek ( ) . first < A . get ( i ) ) s . pop ( ) ; right [ i ] = s . peek ( ) . second ; pair < Integer , Integer > y = new pair < > ( ) ; y . first = A . get ( i ) ; y . second = i ; s . push ( y ) ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( left [ i ] + 1 ) ; System . out . print ( " ▁ " ) ; System . out . println ( right [ i ] - 1 ) ; } } public static void main ( String [ ] args ) { ArrayList < Integer > arr = new ArrayList < > ( ) ; arr . add ( 1 ) ; arr . add ( 3 ) ; arr . add ( 2 ) ; int n = arr . size ( ) ; MaxRange ( arr , n ) ; } }