Count subarrays for every array element in which they are the minimum | Set 2 | C # program for the above approach ; 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
using System ; using System . Collections . Generic ; class GFG { public class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void minSubarray ( int [ ] arr , int N ) { int [ ] result = new int [ N ] ; Stack < pair > l = new Stack < pair > ( ) ; Stack < pair > r = new Stack < pair > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { int count = 1 ; while ( l . Count != 0 && l . Peek ( ) . first > arr [ i ] ) { count += l . Peek ( ) . second ; l . Pop ( ) ; } l . Push ( new pair ( arr [ i ] , count ) ) ; result [ i ] = count ; } for ( int i = N - 1 ; i >= 0 ; i -- ) { int count = 1 ; while ( r . Count != 0 && r . Peek ( ) . first >= arr [ i ] ) { count += r . Peek ( ) . second ; r . Pop ( ) ; } r . Push ( new pair ( arr [ i ] , count ) ) ; result [ i ] *= count ; } for ( int i = 0 ; i < N ; i ++ ) { Console . Write ( result [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 , 4 } ; int N = arr . Length ; minSubarray ( arr , N ) ; } }