Count of subarrays whose maximum element is greater than k | C ++ program to count number 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubarray ( int arr [ ] , int n , int k ) { int s = 0 ; int i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } int count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } s += ( ( count * ( count + 1 ) ) / 2 ) ; } return ( n * ( n + 1 ) / 2 - s ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubarray ( arr , n , k ) ; return 0 ; }