Count subarrays for every array element in which they are the minimum | Set 2 | Function to count subarrays for each element where it is the minimum ; For the length of strictly larger numbers on the left of A [ i ] ; Storing x in result [ i ] ; For the length of strictly larger numbers on the right of A [ i ] ; Store x * y in result array ; Print the result ; Driver Code ; Function Call
function minSubarray ( arr , N ) { let result = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) result [ i ] = 0 ; let l = [ ] ; let r = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { let count = 1 ; while ( l . length != 0 && l [ l . length - 1 ] [ 0 ] > arr [ i ] ) { count += l [ l . length - 1 ] [ 1 ] ; l . pop ( ) ; } l . push ( [ arr [ i ] , count ] ) ; result [ i ] = count ; } for ( let i = N - 1 ; i >= 0 ; i -- ) { let count = 1 ; while ( r . length != 0 && r [ r . length - 1 ] [ 0 ] >= arr [ i ] ) { count += r [ r . length - 1 ] [ 1 ] ; r . pop ( ) ; } r . push ( [ arr [ i ] , count ] ) ; result [ i ] *= count ; } for ( let i = 0 ; i < N ; i ++ ) { document . write ( result [ i ] + " " ) ; } } let arr = [ 3 , 2 , 1 , 4 ] ; let N = arr . length ; minSubarray ( arr , N ) ;