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 ] ; Array . Fill ( nsmr , n ) ; Stack st = new Stack ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { while ( st . Count > 0 && arr [ ( int ) st . Peek ( ) ] >= arr [ i ] ) st . Pop ( ) ; nsmr [ i ] = ( st . Count > 0 ) ? ( int ) st . Peek ( ) : n ; st . Push ( i ) ; } while ( st . Count > 0 ) st . Pop ( ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( st . Count > 0 && arr [ ( int ) st . Peek ( ) ] >= arr [ i ] ) st . Pop ( ) ; nsml [ i ] = ( st . Count > 0 ) ? ( int ) st . Peek ( ) : - 1 ; st . Push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) {