Count of subarrays whose maximum element is greater than k | Return number of subarrays whose maximum element is less than or equal to K . ; To store count of subarrays with all elements less than or equal to k . ; Traversing the array . ; If element is greater than k , ignore . ; Counting the subarray length whose each element is less than equal to k . ; Suming number of subarray whose maximum element is less than equal to k . ; Driver code
function countSubarray ( arr , n , k ) { let s = 0 ; let i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } let count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } s += parseInt ( ( count * ( count + 1 ) ) / 2 , 10 ) ; } return ( n * parseInt ( ( n + 1 ) / 2 , 10 ) - s ) ; } let arr = [ 1 , 2 , 3 ] ; let k = 2 ; let n = arr . length ; document . write ( countSubarray ( arr , n , k ) ) ;