Count of Array elements greater than all elements on its left and next K elements on its right | 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
function countElements ( arr , n , k ) { var s = [ ] ; var next_greater = new Array ( n + 1 ) . fill ( n ) ; for ( var i = 0 ; i < n ; i ++ ) { if ( s . length === 0 ) { s . push ( i ) ; continue ; } while ( s . length !== 0 && arr [ s [ s . length - 1 ] ] < arr [ i ] ) { next_greater [ s [ s . length - 1 ] ] = i ; s . pop ( ) ; } s . push ( i ) ; } var count = 0 ; var maxi = - 2147483648 ; for ( var i = 0 ; i < n ; i ++ ) { if ( next_greater [ i ] - i > k && maxi < arr [ i ] ) { maxi = Math . max ( maxi , arr [ i ] ) ; count ++ ; } } return count ; } var arr = [ 4 , 2 , 3 , 6 , 4 , 3 , 2 ] ; var K = 2 ; var n = arr . length ; document . write ( countElements ( arr , n , K ) ) ;