Count of Array elements greater than or equal to twice the Median of K trailing Array elements | Javascript Program to implement the above approach ; Function to find the count of array elements >= twice the median of K trailing array elements ; Stores frequencies ; Stores the array elements ; Count the frequencies of the array elements ; Iterating from d to n - 1 index means ( d + 1 ) th element to nth element ; To check the median ; Iterate over the frequencies of the elements ; Add the frequencies ; Check if the low_median value is obtained or not , if yes then do not change as it will be minimum ; Check if the high_median value is obtained or not , if yes then do not change it as it will be maximum ; Store 2 * median of K trailing elements ; If the current >= 2 * median ; Decrease the frequency for ( k - 1 ) - th element ; Increase the frequency of the current element ; Print the count ; Driver Code
const N = 2e5 ; const V = 500 ; function solve ( n , d , input ) { let a = new Array ( N ) ; let cnt = new Array ( V + 1 ) ; for ( let i = 0 ; i < n ; ++ i ) a [ i ] = input [ i ] ; let answer = 0 ; for ( let i = 0 ; i < d ; ++ i ) cnt [ a [ i ] ] ++ ; for ( let i = d ; i <= n - 1 ; ++ i ) { let acc = 0 ; let low_median = - 1 , high_median = - 1 ; for ( let v = 0 ; v <= V ; ++ v ) { acc += cnt [ v ] ; if ( low_median == - 1 && acc >= parseInt ( Math . floor ( ( d + 1 ) / 2.0 ) ) ) low_median = v ; if ( high_median == - 1 && acc >= parseInt ( Math . ceil ( ( d + 1 ) / 2.0 ) ) ) high_median = v ; } let double_median = low_median + high_median ; if ( a [ i ] >= double_median ) answer ++ ; cnt [ a [ i - d ] ] -- ; cnt [ a [ i ] ] ++ ; } document . write ( answer ) ; } let input = [ 1 , 2 , 2 , 4 , 5 ] ; let n = input . length ; let k = 3 ; solve ( n , k , input ) ;