Count of Array elements greater than all elements on its left and next K elements on its right | C # program to implement the above approach ; Function to print the count of Array elements greater than all elements on its left and next K elements on its right ; Iterate over the array ; If the stack is not empty and the element at the top of the stack is smaller than arr [ i ] ; Store the index of next greater element ; Pop the top element ; Insert the current index ; Stores the count ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static int countElements ( int [ ] arr , int n , int k ) { Stack < int > s = new Stack < int > ( ) ; int [ ] next_greater = new int [ n + 1 ] ; Array . Fill ( next_greater , n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . Count == 0 ) { s . Push ( i ) ; continue ; } while ( s . Count != 0 && arr [ s . Peek ( ) ] < arr [ i ] ) { next_greater [ s . Peek ( ) ] = i ; s . Pop ( ) ; } s . Push ( i ) ; } int count = 0 ; int maxi = Int32 . MinValue ; for ( int i = 0 ; i < n ; i ++ ) { if ( next_greater [ i ] - i > k && maxi < arr [ i ] ) { maxi = Math . Max ( maxi , arr [ i ] ) ; count ++ ; } } return count ; } static void Main ( ) { int [ ] arr = { 4 , 2 , 3 , 6 , 4 , 3 , 2 } ; int K = 2 ; int n = arr . Length ; Console . Write ( countElements ( arr , n , K ) ) ; } }