Open In App

Count of subarrays whose maximum element is greater than k

Given an array of n elements and an integer k. The task is to find the count of the subarray which has a maximum element greater than K.

Examples : 

Input : arr[] = {1, 2, 3} and k = 2.
Output : 3
All the possible subarrays of arr[] are
{ 1 }, { 2 }, { 3 }, { 1, 2 }, { 2, 3 },
{ 1, 2, 3 }.
Their maximum elements are 1, 2, 3, 2, 3, 3.
There are only 3 maximum elements > 2.
Recommended Practice

Approach 1: Counting Subarrays having max element <= K and then subtracting from total subarrays.

The idea is to approach problem by counting subarrays whose maximum element is less than or equal to k as counting such subarrays is easier. To find the number of subarray whose maximum element is less than or equal to k, remove all the element which is greater than K and find the number of subarray with the left elements. 

Once we find above count, we can subtract it from n*(n+1)/2 to get our required result. Observe, there can be n*(n+1)/2 possible number of subarray of any array of size n. So, finding the number of subarray whose maximum element is less than or equal to K and subtracting it from n*(n+1)/2 gets us the answer.

Below is the implementation of this approach:




// C++ program to count number of subarrays
// whose maximum element is greater than K.
#include <bits/stdc++.h>
using namespace std;
  
// Return number of subarrays whose maximum
// element is less than or equal to K.
int countSubarray(int arr[], int n, int k)
{
    // To store count of subarrays with all
    // elements less than or equal to k.
    int s = 0;
  
    // Traversing the array.
    int i = 0;
    while (i < n) {
        // If element is greater than k, ignore.
        if (arr[i] > k) {
            i++;
            continue;
        }
  
        // Counting the subarray length whose
        // each element is less than equal to k.
        int count = 0;
        while (i < n && arr[i] <= k) {
            i++;
            count++;
        }
  
        // Summing number of subarray whose
        // maximum element is less than equal to k.
        s += ((count * (count + 1)) / 2);
    }
  
    return (n * (n + 1) / 2 - s);
}
  
// Driven Program
int main()
{
    int arr[] = { 1, 2, 3 };
    int k = 2;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countSubarray(arr, n, k);
    return 0;
}




// Java program to count number of subarrays
// whose maximum element is greater than K.
import java.util.*;
  
class GFG {
  
    // Return number of subarrays whose maximum
    // element is less than or equal to K.
    static int countSubarray(int arr[], int n, int k)
    {
  
        // To store count of subarrays with all
        // elements less than or equal to k.
        int s = 0;
  
        // Traversing the array.
        int i = 0;
        while (i < n) {
  
            // If element is greater than k, ignore.
            if (arr[i] > k) {
                i++;
                continue;
            }
  
            // Counting the subarray length whose
            // each element is less than equal to k.
            int count = 0;
            while (i < n && arr[i] <= k) {
                i++;
                count++;
            }
  
            // Summing number of subarray whose
            // maximum element is less than equal to k.
            s += ((count * (count + 1)) / 2);
        }
  
        return (n * (n + 1) / 2 - s);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int arr[] = { 1, 2, 3 };
        int k = 2;
        int n = arr.length;
        System.out.print(countSubarray(arr, n, k));
    }
}
  
// This code is contributed by Anant Agarwal.




# Python 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.
def countSubarray(arr, n, k):
  
    # To store count of
    # subarrays with all
    # elements less than
    # or equal to k.
    s = 0
   
    # Traversing the array.
    i = 0
    while (i < n):
      
        # If element is greater
        # than k, ignore.
        if (arr[i] > k):
          
            i = i + 1
            continue
          
        # Counting the subarray
        # length whose
        # each element is less
        # than equal to k.
        count = 0
        while (i < n and arr[i] <= k):
          
            i = i + 1
            count = count + 1
          
   
        # Summing number of subarray whose
        # maximum element is less
        # than equal to k.
        s = s + ((count*(count + 1))//2)
      
   
    return (n*(n + 1)//2 - s)
      
# Driver code
  
arr = [1, 2, 3]
k = 2
n = len(arr)
  
print(countSubarray(arr, n, k))
  
# This code is contributed
# by Anant Agarwal.




// C# program to count number of subarrays
// whose maximum element is greater than K.
using System;
  
class GFG {
  
    // Return number of subarrays whose maximum
    // element is less than or equal to K.
    static int countSubarray(int[] arr, int n, int k)
    {
        // To store count of subarrays with all
        // elements less than or equal to k.
        int s = 0;
  
        // Traversing the array.
        int i = 0;
        while (i < n) {
  
            // If element is greater than k, ignore.
            if (arr[i] > k) {
                i++;
                continue;
            }
  
            // Counting the subarray length whose
            // each element is less than equal to k.
            int count = 0;
            while (i < n && arr[i] <= k) {
                i++;
                count++;
            }
  
            // Summing number of subarray whose
            // maximum element is less than equal to k.
            s += ((count * (count + 1)) / 2);
        }
  
        return (n * (n + 1) / 2 - s);
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = {1, 2, 3};
        int k = 2;
        int n = arr.Length;
        Console.WriteLine(countSubarray(arr, n, k));
    }
}
  
// This code is contributed by vt_m.




<script>
    // Javascript 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.
    function countSubarray(arr, n, k)
    {
        // To store count of subarrays with all
        // elements less than or equal to k.
        let s = 0;
    
        // Traversing the array.
        let i = 0;
        while (i < n) {
    
            // If element is greater than k, ignore.
            if (arr[i] > k) {
                i++;
                continue;
            }
    
            // Counting the subarray length whose
            // each element is less than equal to k.
            let count = 0;
            while (i < n && arr[i] <= k) {
                i++;
                count++;
            }
    
            // Summing number of subarray whose
            // maximum element is less than equal to k.
            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));
      
</script>




<?php
// PHP 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.
function countSubarray( $arr, $n, $k)
{
      
    // To store count of subarrays with all
    // elements less than or equal to k.
    $s = 0;
  
    // Traversing the array.
    $i = 0;
    while ($i < $n) {
          
        // If element is greater than k,
        // ignore.
        if ($arr[$i] > $k) {
            $i++;
            continue;
        }
  
        // Counting the subarray length 
        // whose each element is less
        // than equal to k.
        $count = 0;
        while ($i < $n and $arr[$i] <= $k) {
            $i++;
            $count++;
        }
  
        // Summing number of subarray whose
        // maximum element is less than
        // equal to k.
        $s += (($count * ($count + 1)) / 2);
    }
  
    return ($n * ($n + 1) / 2 - $s);
}
  
// Driven Program
    $arr = array( 1, 2, 3 );
    $k = 2;
    $n = count($arr);
    echo countSubarray($arr, $n, $k);
  
// This code is contributed by anuj_67.
?>

Output
3


Time Complexity: O(n).
Auxiliary Space: O(1)

Approach 2: Counting Subarrays having max element > K

In this approach we just simply find the count of subarrays that can be formed by including an element at index i which is greater than K. Therefore, if suppose arr [ i ] > K then all the subarrays in which this element is present will have a value which is greater than k, so we just calculate all of these subarrays for every element that is greater than K and add them in answer. We first initialize two variables ans = 0 this contains answer and prev = -1 this keeps track of index of previous element that was greater than K.

To do this we just need three values for every arr [ i ] > K .

  1. Number of subarrays starting from the index i. This will be ( N – i ) . NOTE: In this we have included the subarray containing single element that is this element itself. { arr [ i ] }
  2. Number of subarrays ending at this index i but starting index of these subarrays is after the index prev of previous element that was greater than K, why do we do this? Because for that elements we must have already calculated our answer so we dont want to count same subarrays more than once. So, this value will be comes to be ( i – prev – 1 ) . NOTE: In this we subtract 1 because we have already counted a subarray { arr [ i ] } having itself as single element. See above point note. 
  3. Number of subarrays having starting index less than i but greater than prev , and ending index greater than i. Therefore all subarrays in which arr[i] is in between. This we can calculate by multiplying above two values. Lets say them as L = ( N – i – 1 ) and R = (  i  – prev -1 ). Now we just multiply these L and R because for every 1 index on left side of i there are R index that can make different subarrays basic maths thing. So, this becomes L * R . Notice here in val of L we have actually subtracted 1 if we dont do this then we include index i in our L*R which will mean we have included number 1 type subarrays again. See point 1.   

Below is the implementation of this approach:




// C++ program to count number of subarrays
// whose maximum element is greater than K.
#include <bits/stdc++.h>
using namespace std;
  
long long countSubarray(int arr[], int n, int k)
{
    long long ans = 0 ;
        int prev = - 1; //prev for keeping track of index of previous element > k;
        for(int i = 0 ; i < n ; i++ ) {
           if ( arr [ i ] > k ) {
              ans += n - i ; //subarrays starting at index i.
              ans += i - prev - 1 ; //subarrays ending at index i but starting after prev.
              ans += ( n - i - 1 ) * 1LL * ( i - prev - 1 ) ; //subarrays having index i element in between.
              prev = i; // updating prev
           }
        }
        return ans;
}
  
// Driven Program
int main()
{
    int arr[] = { 4, 5, 1, 2, 3 };
    int k = 2;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countSubarray(arr, n, k);
    return 0;
}
// This Code is contributed by Manjeet Singh.




// Java program to count number of subarrays
// whose maximum element is greater than K.
import java.util.*;
  
public class GFG {
  
    static long countSubarray(int arr[], int n, int k)
    {
      long ans = 0 ;
        int prev = - 1; //prev for keeping track of index of previous element > k;
        for(int i = 0 ; i < n ; i++ ) {
           if ( arr [ i ] > k ) {
              ans += n - i ; //subarrays starting at index i.
              ans += i - prev - 1 ; //subarrays ending at index i but starting after prev.
              ans += ( n - i - 1 ) * 1L * ( i - prev - 1 ) ; //subarrays having index i element in between.
              prev = i; // updating prev
           }
        }
        return ans;
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int arr[] = { 4, 5, 1, 2, 3 };
        int k = 2;
        int n = arr.length;
        System.out.print(countSubarray(arr, n, k));
    }
}
  
//This Code is contributed by Manjeet Singh




# Python program to count number of subarrays
# whose maximum element is greater than K.
  
def countSubarray( arr,  n,  k):
    ans = 0 ;
    prev = - 1; #prev for keeping track of index of previous element > k;
    for i in range(0,n):
        if ( arr [ i ] > k ) :
            ans += n - i ; #subarrays starting at index i.
            ans += i - prev - 1 ; #subarrays ending at index i but starting after prev.
            ans += ( n - i - 1 * ( i - prev - 1 ) ; #subarrays having index i element in between.
            prev = i; # updating prev
         
    return ans;
  
# Driven Program
arr = [ 4, 5, 1, 2, 3 ];
k = 2;
n = len(arr);
print(countSubarray(arr, n, k));
  
# this code is contributed by poojaagarwal2.




// C# program to count number of subarrays
// whose maximum element is greater than K.
  
using System;
  
public class GFG {
  
    static long countSubarray(int[] arr, int n, int k)
    {
        long ans = 0;
        int prev = -1; // prev for keeping track of index of
                       // previous element > k;
        for (int i = 0; i < n; i++) {
            if (arr[i] > k) {
                ans += n - i; // subarrays starting at index
                              // i.
                ans += i - prev
                       - 1; // subarrays ending at index i
                            // but starting after prev.
                ans += (n - i - 1) * (long)1
                       * (i - prev
                          - 1); // subarrays having index i
                                // element in between.
                prev = i; // updating prev
            }
        }
        return ans;
    }
  
    // Driver code
    public static void Main(string[] args)
    {
  
        int[] arr = { 4, 5, 1, 2, 3 };
        int k = 2;
        int n = arr.Length;
        Console.Write(countSubarray(arr, n, k));
    }
}
  
// This Code is contributed by Karandeep1234




// Javascript program to count number of subarrays
// whose maximum element is greater than K.
  
function countSubarray(arr, n, k)
{
    let ans = 0 ;
    //prev for keeping track of index of previous element > k;
    let prev = - 1; 
    for(let i = 0 ; i < n ; i++ ) {
       if ( arr [ i ] > k ) {
       //subarrays starting at index i.
          ans += n - i ; 
           //subarrays ending at index i but starting after prev.
          ans += i - prev - 1 ;
          //subarrays having index i element in between.
          ans += ( n - i - 1 ) * 1 * ( i - prev - 1 ) ; 
          // updating prev
          prev = i; 
       }
    }
    return ans;
}
  
// Driven Program
    let arr = [ 4, 5, 1, 2, 3 ];
    let k = 2;
    let n = arr.length;
    document.write(countSubarray(arr, n, k));

Output
12


Time Complexity: O(n).

Approach 3 : Sliding Window Technique.

Algorithm:

1. Initialize a variable ans = 0 , a varialble maxElement = 0 and a variable count = 0 .

2. Iterate through the array, doing the following for each element:

  a. If the current element i.e. arr[ i ] is greater than current maximum , update the maximum i.e. maxElement = arr[ i ] and reset the count to 0.

  b. If the current element is less than or eual to the current maximum, then increment the count.

  c. If maxElement is grteater than k, then add count of subarrays to final answer and update the maxElement to current element.

3. Return Final answer.

Here’s the the implementation of Sliding window technique.




#include <bits/stdc++.h>
using namespace std;
  
int countSubarray(int arr[], int n, int k) {
    int maxElement = 0, count = 0, ans = 0;
    for(int i=0; i<n; i++) {
        if(arr[i] > maxElement) {
            maxElement = arr[i];
            count = 0;
        }
        else {
            count++;
        }
        if(maxElement > k) {
            ans += (i - count + 1);
            maxElement = arr[i];
            count = 0;
        }
    }
    return ans;
}
int main()
{
    int arr[] = {1, 2, 3, 4};
    int k = 1;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countSubarray(arr, n, k);
    return 0;
}
// This code is contributed by  Vaibhav Saroj




#include <stdio.h>
  
int countSubarray(int arr[], int n, int k) {
    int maxElement = 0, count = 0, ans = 0;
    for(int i=0; i<n; i++) {
        if(arr[i] > maxElement) {
            maxElement = arr[i];
            count = 0;
        }
        else {
            count++;
        }
        if(maxElement > k) {
            ans += (i - count + 1);
            maxElement = arr[i];
            count = 0;
        }
    }
    ans += (count * (count + 1)) / 2;
    return ans;
}
  
int main() {
    int arr[] = {1, 2, 3, 4};
    int k = 1;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("%d\n", countSubarray(arr, n, k));
    return 0;
}
// This code is contributed by  Vaibhav Saroj




import java.util.*;
  
public class GFG {
    // Function to count the number of subarrays with the maximum element greater than k
    public static int countSubarray(int[] arr, int n, int k) {
        int maxElement = 0; // Variable to store the maximum element encountered so far
        int count = 0;      // Variable to count the length of the subarray with elements <= k
        int ans = 0;        // Variable to store the final result
  
        for (int i = 0; i < n; i++) {
            if (arr[i] > maxElement) {
                // If the current element is greater than the maximum element
                // update the maximum element and reset the count to zero.
                maxElement = arr[i];
                count = 0;
            } else {
                // increment the count
                count++;
            }
  
            if (maxElement > k) {
                // If the maximum element in the current subarray is greater than k,
                // add the count of subarrays ending at the current index (i - count + 1) to the result.
                ans += (i - count + 1);
  
                // Reset the maximum element and count to zero.
                maxElement = arr[i];
                count = 0;
            }
        }
  
        // Return the final result
        return ans;
    }
  
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        int k = 1;
        int n = arr.length;
  
        // Call the countSubarray function to count the number of subarrays with maximum element greater than k
        int result = countSubarray(arr, n, k);
        System.out.println(result);
    }
}
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL




def countSubarray(arr, n, k):
    maxElement, count, ans = 0, 0, 0
    for i in range(n):
        if arr[i] > maxElement:
            maxElement = arr[i]
            count = 0
        else:
            count += 1
        if maxElement > k:
            ans += (i - count + 1)
            maxElement = arr[i]
            count = 0
    ans += (count * (count + 1)) // 2
    return ans
  
arr = [1, 2, 3, 4]
k = 1
n = len(arr)
print(countSubarray(arr, n, k))
  
# This code is contributed by  Vaibhav Saroj




using System;
  
public class Program {
    public static int CountSubarray(int[] arr, int n, int k) {
        int maxElement = 0, count = 0, ans = 0;
        for(int i=0; i<n; i++) {
            if(arr[i] > maxElement) {
                maxElement = arr[i];
                count = 0;
            }
            else {
                count++;
            }
            if(maxElement > k) {
                ans += (i - count + 1);
                maxElement = arr[i];
                count = 0;
            }
        }
        ans += (count * (count + 1)) / 2;
        return ans;
    }
  
    public static void Main() {
        int[] arr = {1, 2, 3, 4};
        int k = 1;
        int n = arr.Length;
        Console.WriteLine(CountSubarray(arr, n, k));
    }
}
  
// This code is contributed by  Vaibhav Saroj




function countSubarray(arr, n, k) {
    let maxElement = 0, count = 0, ans = 0;
    for(let i=0; i<n; i++) {
        if(arr[i] > maxElement) {
            maxElement = arr[i];
            count = 0;
        }
        else {
            count++;
        }
        if(maxElement > k) {
            ans += (i - count + 1);
            maxElement = arr[i];
            count = 0;
        }
    }
    ans += (count * (count + 1)) / 2;
    return ans;
}
  
let arr = [1, 2, 3, 4];
let k = 1;
let n = arr.length;
console.log(countSubarray(arr, n, k));
  
// This code is contributed by  Vaibhav Saroj

Output
9


The Sliding Window Technique is contributed by Vaibhav Saroj .

Time Complexity: O( n ).
Space Complexity: O( 1 ).

Practice here Count of Subarrays .


Article Tags :