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 . ; Driver Code ; Given Input ; Function Call
def totalSubarrays ( arr , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT count = 0 NEW_LINE while ( i < n and arr [ i ] <= k ) : NEW_LINE INDENT i += 1 NEW_LINE count += 1 NEW_LINE DEDENT ans += ( ( count * ( count + 1 ) ) // 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def countSubarrays ( arr , n , k ) : NEW_LINE INDENT count1 = totalSubarrays ( arr , n , k - 1 ) NEW_LINE count2 = totalSubarrays ( arr , n , k ) NEW_LINE ans = count2 - count1 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE k = 3 NEW_LINE arr = [ 2 , 1 , 3 , 4 ] NEW_LINE print ( countSubarrays ( arr , n , k ) ) NEW_LINE DEDENT