Count subarrays with all elements greater than K in C++


We are given an array arr[] of integers. Also a number K. The goal is to count all subarrays of arr[] such that all elements of the subarray are greater than K or K is less than all elements of the subarrays. If the array is [1,2,3] and K is 1. Subarrays will be [2], [3], [2,3].

Let us understand with examples.

Input − arr[] = { 2, 2, 1, 1, 1, 5 }; K=1

Output − Count of subarrays with all elements greater than K are − 4

Explanation − Subaarays will be: [2], [2], [5], [2,2]. All elements in each subarray are greater than 1.

Input − arr[] = { 3,4,5,6 }; K=2

Output − Count of subarrays with all elements greater than K are − 10

Explanation − Subaarays will be − [3], [4], [5], [6], [3,4], [4,5], [5,6], [3,4,5], [4,5,6], [3,4,5,6]. Total count=10.

The approach used in the below program is as follows

We will traverse the array using a for a loop. If the current element is greater than K. Increment count. Otherwise set count=0 and total=count*(count+1)/2. (for subarrays). If at the end count is non-zero. Add count*(count+1)/2 for a count of remaining subarrays.

  • Take an array arr[] of numbers.

  • Function sub_greater_k(int arr[], int size, int k) takes the array and returns a count of subarrays with all elements greater than k.

  • Take the initial count as 0.

  • We will traverse the array using for loops from i=0 to i<size.

  • If arr[i]>k then increment count.

  • Subarrays with count (elements > k ) will be count*(count+1)/2. Add this to the total for all such subarrays.

  • At the end of again add count*(count+1)/2 to total if the count is non-zero.

  • Return total as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int sub_greater_k(int arr[], int size, int k){
   int count = 0;
   int total = 0;
   for (int i = 0; i < size; i++){
      if (arr[i] > k){
         count++;
      }
      else{
         total += (count) * (count + 1) / 2;
         count = 0;
      }
   }
   if(count){
      total += (count) * (count + 1) / 2;
   }
   return total;
}
int main(){
   int arr[] = {2, 4, 6, 1, 3, 7, 9 };
   int size = sizeof(arr) / sizeof(arr[0]);
   int k = 7;
   cout<<"Count of subarrays with all elements greater than K are: "<<sub_greater_k(arr, size, k);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of subarrays with all elements greater than K are: 1

Updated on: 01-Dec-2020

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements