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 . ; Driven Program
< ? php function countSubarray ( $ arr , $ n , $ k ) { $ s = 0 ; $ i = 0 ; while ( $ i < $ n ) { if ( $ arr [ $ i ] > $ k ) { $ i ++ ; continue ; } $ count = 0 ; while ( $ i < $ n and $ arr [ $ i ] <= $ k ) { $ i ++ ; $ count ++ ; } $ s += ( ( $ count * ( $ count + 1 ) ) / 2 ) ; } return ( $ n * ( $ n + 1 ) / 2 - $ s ) ; } $ arr = array ( 1 , 2 , 3 ) ; $ k = 2 ; $ n = count ( $ arr ) ; echo countSubarray ( $ arr , $ n , $ k ) ; ? >