For finding next smaller element right to a element if there is no next smaller element right to it than taking n .
int nsmr [ ] = new int [ n ] ; Arrays . fill ( nsmr , n ) ; Stack < Integer > st = new Stack < Integer > ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( st . size ( ) > 0 && arr [ ( int ) st . peek ( ) ] >= arr [ i ] ) st . pop ( ) ; nsmr [ i ] = ( st . size ( ) > 0 ) ? ( int ) st . peek ( ) : n ; st . push ( i ) ; } while ( st . size ( ) > 0 ) st . pop ( ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( st . size ( ) > 0 && arr [ ( int ) st . peek ( ) ] >= arr [ i ] ) st . pop ( ) ; nsml [ i ] = ( st . size ( ) > 0 ) ? ( int ) st . peek ( ) : - 1 ; st . push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) {