Count of subarrays with maximum value as K | Function to count the subarrays with maximum not greater than K ; If arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; Count the number of elements where arr [ i ] is not greater than k . ; Summation of all possible subarrays in the variable ans . ; Function to count the subarrays with maximum value is equal to K ; Stores count of subarrays with max <= k - 1. ; Stores count of subarrays with max >= k + 1. ; Stores count of subarrays with max = k . ; Given Input ; Function Call
function totalSubarrays ( arr , n , k ) { let ans = 0 , i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } let count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } ans += ( Math . floor ( ( count * ( count + 1 ) ) / 2 ) ) ; } return ans ; } function countSubarrays ( arr , n , k ) { let count1 = totalSubarrays ( arr , n , k - 1 ) ; let count2 = totalSubarrays ( arr , n , k ) ; let ans = count2 - count1 ; return ans ; } let n = 4 , k = 3 ; let arr = [ 2 , 1 , 3 , 4 ] ; document . write ( countSubarrays ( arr , n , k ) ) ;