Count of Array elements greater than all elements on its left and next K elements on its right | Python3 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
import sys NEW_LINE def countElements ( arr , n , k ) : NEW_LINE INDENT s = [ ] NEW_LINE next_greater = [ n ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( i ) NEW_LINE continue NEW_LINE DEDENT while ( len ( s ) != 0 and arr [ s [ - 1 ] ] < arr [ i ] ) : NEW_LINE INDENT next_greater [ s [ - 1 ] ] = i NEW_LINE s . pop ( - 1 ) NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT count = 0 NEW_LINE maxi = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( next_greater [ i ] - i > k and maxi < arr [ i ] ) : NEW_LINE INDENT maxi = max ( maxi , arr [ i ] ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 3 , 6 , 4 , 3 , 2 ] NEW_LINE K = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( countElements ( arr , n , K ) ) NEW_LINE DEDENT