Count subarrays for every array element in which they are the minimum | C # implementation of the above approach ; Function to required count subarrays ; For storing count of subarrays ; For finding next smaller element left to a element if there is no next smaller element left to it than taking - 1. ; For finding next smaller element right to a element if there is no next smaller element right to it than taking n . ; Taking exact boundaries in which arr [ i ] is minimum ; Similarly for right side ; Driver code ; Given array arr [ ] ; Function call
using System ; using System . Collections ; class GFG { static int [ ] countingSubarray ( int [ ] arr , int n ) { int [ ] a = new int [ n ] ; int [ ] nsml = new int [ n ] ; Array . Fill ( nsml , - 1 ) ; 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 ++ ) { nsml [ i ] ++ ; nsmr [ i ] -- ; int r = nsmr [ i ] - i + 1 ; int l = i - nsml [ i ] + 1 ; a [ i ] = r * l ; } return a ; } static void Main ( ) { int N = 5 ; int [ ] arr = { 3 , 2 , 4 , 1 , 5 } ; int [ ] a = countingSubarray ( arr , N ) ; Console . Write ( " [ " ) ; int n = a . Length - 1 ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( a [ i ] + " , ▁ " ) ; Console . Write ( a [ n ] + " ] " ) ; } }