Count subarrays which contains both the maximum and minimum array element

Given an array arr[] consisting of N distinct integers, the task is to find the number of subarrays which contains both the maximum and the minimum element from the given array.

Examples:

Input: arr[] = {1, 2, 3, 4}
Output:
Explanation:  
Only a single subarray {1, 2, 3, 4} consists of both the maximum (= 4) and the minimum (= 1) array elements.

Input: arr[] = {4, 1, 2, 3}
Output: 3
Explanation:  
Subrrays {4, 1}  , {4, 1, 2}, {4, 1, 2, 3}  consists of both the maximum(= 4) and the minimum(= 1) array elements .

Naive Approach: The simplest approach is to first, traverse the array and find the maximum and minimum of the array and then generate all possible subarrays of the given array. For each subarray, check if it contains both the maximum and the minimum array element. For all such subarrays, increase the count by 1. Finally, print the count of such subarrays.
Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach:  Follow the steps below to optimize the above approach:



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count subarray
// containing  both maximum and
// minimum array elements
int countSubArray(int arr[], int n)
{
    // If the length of the
    // array is less than 2
    if (n < 2)
        return n;
 
    // Find the index of maximum element
    int i
        = max_element(arr, arr + n) - arr;
 
    // Find the index of minimum element
    int j
        = min_element(arr, arr + n) - arr;
 
    // If i > j, then swap
    // the value of i and j
    if (i > j)
        swap(i, j);
 
    // Return the answer
    return (i + 1) * (n - j);
}
 
// Driver Code
int main()
{
    int arr[] = { 4, 1, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    // Function call
    cout << countSubArray(arr, n);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to count subarray
// containing both maximum and
// minimum array elements
static int countSubArray(int arr[], int n)
{
     
    // If the length of the
    // array is less than 2
    if (n < 2)
        return n;
 
    // Find the index of maximum element
    int i = max_element(arr);
 
    // Find the index of minimum element
    int j = min_element(arr);
 
    // If i > j, then swap
    // the value of i and j
    if (i > j)
    {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
         
    // Return the answer
    return (i + 1) * (n - j);
}
 
// Function to return max_element index
static int max_element(int[] arr)
{
    int idx = 0;
    int max = arr[0];
    for(int i = 1; i < arr.length; i++)
    {
        if(max < arr[i])
        {
            max = arr[i];
            idx = i;
        }
    }
    return idx;
}
 
// Function to return min_element index
static int min_element(int[] arr)
{
    int idx = 0;
    int min = arr[0];
    for(int i = 1; i < arr.length; i++)
    {
        if (arr[i] < min)
        {
            min = arr[i];
            idx = i;
        }
    }
    return idx;
}
 
// Driver Code
public static void main (String[] args)
{
    int arr[] = { 4, 1, 2, 3 };
    int n = arr.length;
     
    // Function call
    System.out.println(countSubArray(arr, n));
}
}
 
// This code is contributed by offbeat
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for
# the above approach
 
# Function to count subarray
# containing both maximum and
# minimum array elements
def countSubArray(arr, n):
   
    # If the length of the
    # array is less than 2
    if (n < 2):
        return n;
 
    # Find the index of
    # maximum element
    i = max_element(arr);
 
    # Find the index of
    # minimum element
    j = min_element(arr);
 
    # If i > j, then swap
    # the value of i and j
    if (i > j):
        tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
 
    # Return the answer
    return (i + 1) * (n - j);
 
# Function to return
# max_element index
def max_element(arr):
    idx = 0;
    max = arr[0];
     
    for i in range(1, len(arr)):
        if (max < arr[i]):
            max = arr[i];
            idx = i;
    return idx;
 
# Function to return
# min_element index
def min_element(arr):
    idx = 0;
    min = arr[0];
     
    for i in range(1, len(arr)):
        if (arr[i] < min):
            min = arr[i];
            idx = i;
 
    return idx;
 
# Driver Code
if __name__ == '__main__':
    arr = [4, 1, 2, 3];
    n = len(arr);
 
    # Function call
    print(countSubArray(arr, n));
 
# This code is contributed by Rajput-Ji
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for
// the above approach
using System;
class GFG{
     
// Function to count subarray
// containing both maximum and
// minimum array elements
static int countSubArray(int []arr,
                         int n)
{   
  // If the length of the
  // array is less than 2
  if (n < 2)
    return n;
 
  // Find the index of maximum element
  int i = max_element(arr);
 
  // Find the index of minimum element
  int j = min_element(arr);
 
  // If i > j, then swap
  // the value of i and j
  if (i > j)
  {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
 
  // Return the answer
  return (i + 1) * (n - j);
}
 
// Function to return max_element index
static int max_element(int[] arr)
{
  int idx = 0;
  int max = arr[0];
  for(int i = 1; i < arr.Length; i++)
  {
    if(max < arr[i])
    {
      max = arr[i];
      idx = i;
    }
  }
  return idx;
}
 
// Function to return min_element index
static int min_element(int[] arr)
{
  int idx = 0;
  int min = arr[0];
  for(int i = 1; i < arr.Length; i++)
  {
    if (arr[i] < min)
    {
      min = arr[i];
      idx = i;
    }
  }
  return idx;
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {4, 1, 2, 3};
  int n = arr.Length;
 
  // Function call
  Console.WriteLine(countSubArray(arr, n));
}
}
 
// This code is contributed by shikhasingrajput
chevron_right

Output: 
3







Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :