Count of Array elements greater than all elements on its left and next K elements on its right | Java 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 java . util . * ; class GFG { static int countElements ( int arr [ ] , int n , int k ) { Stack < Integer > s = new Stack < Integer > ( ) ; int [ ] next_greater = new int [ n + 1 ] ; Arrays . fill ( next_greater , n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( s . isEmpty ( ) ) { s . add ( i ) ; continue ; } while ( ! s . isEmpty ( ) && arr [ s . peek ( ) ] < arr [ i ] ) { next_greater [ s . peek ( ) ] = i ; s . pop ( ) ; } s . add ( i ) ; } int count = 0 ; int maxi = Integer . MIN_VALUE ; 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 3 , 6 , 4 , 3 , 2 } ; int K = 2 ; int n = arr . length ; System . out . print ( countElements ( arr , n , K ) ) ; } }