Count subarrays which contains both the maximum and minimum array element
Last Updated :
11 Nov, 2023
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: 1
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:
Subarrays {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.
Code-
C++
// 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)
{
int maxi=INT_MIN;
int mini=INT_MAX;
for(int i=0;i<n;i++){
maxi=max(maxi,arr[i]);
mini=min(mini,arr[i]);
}
int count=0;
for(int i=0;i<n;i++){
int temp_max=arr[i];
int temp_min=arr[i];
for(int j=i;j<n;j++){
if(arr[j]>temp_max){temp_max=arr[j];}
if(arr[j]<temp_min){temp_min=arr[j];}
//Checking that our subarray will contain
//maximum and minimum element of array
if((mini==temp_min) && (maxi==temp_max) ){
count++;
}
}
}
return count;
}
// 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;
}
Java
import java.util.*;
import java.io.*;
public class GFG {
// Function to count subarrays containing both maximum and minimum array elements
public static int countSubArray(int[] arr, int n) {
int maxi = Integer.MIN_VALUE;
int mini = Integer.MAX_VALUE;
// Finding the maximum and minimum elements in the array
for (int i = 0; i < n; i++) {
maxi = Math.max(maxi, arr[i]);
mini = Math.min(mini, arr[i]);
}
int count = 0;
for (int i = 0; i < n; i++) {
int tempMax = arr[i];
int tempMin = arr[i];
for (int j = i; j < n; j++) {
if (arr[j] > tempMax) {
tempMax = arr[j];
}
if (arr[j] < tempMin) {
tempMin = arr[j];
}
// Checking if the subarray contains the maximum and minimum elements of the array
if (mini == tempMin && maxi == tempMax) {
count++;
}
}
}
return count;
}
// 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));
}
}
Python3
# Function to count subarrays containing both maximum and minimum array elements
def countSubArray(arr):
maxi = float('-inf')
mini = float('inf')
# Finding the maximum and minimum elements in the array
for element in arr:
maxi = max(maxi, element)
mini = min(mini, element)
count = 0
for i in range(len(arr)):
temp_max = arr[i]
temp_min = arr[i]
for j in range(i, len(arr)):
if arr[j] > temp_max:
temp_max = arr[j]
if arr[j] < temp_min:
temp_min = arr[j]
# Checking if the subarray contains the maximum and minimum elements of the array
if mini == temp_min and maxi == temp_max:
count += 1
return count
# Driver code
arr = [4, 1, 2, 3]
result = countSubArray(arr)
print(result)
C#
using System;
class GFG
{
// Function to count subarray
// containing both maximum and
// minimum array elements
static int CountSubArray(int[] arr, int n)
{
int maxi = int.MinValue;
int mini = int.MaxValue;
for (int i = 0; i < n; i++)
{
maxi = Math.Max(maxi, arr[i]);
mini = Math.Min(mini, arr[i]);
}
int count = 0;
for (int i = 0; i < n; i++)
{
int tempMax = arr[i];
int tempMin = arr[i];
for (int j = i; j < n; j++)
{
if (arr[j] > tempMax) tempMax = arr[j];
if (arr[j] < tempMin) tempMin = arr[j];
// Checking that our subarray will contain
// maximum and minimum element of array
if (mini == tempMin && maxi == tempMax)
{
count++;
}
}
}
return count;
}
// Driver Code
static void Main(string[] args)
{
int[] arr = { 4, 1, 2, 3 };
int n = arr.Length;
// Function call
Console.WriteLine(CountSubArray(arr, n));
}
}
JavaScript
// Function to count subarray
// containing both maximum and
// minimum array elements
function countSubArray(arr) {
let maxi = Number.MIN_SAFE_INTEGER;
let mini = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < arr.length; i++) {
maxi = Math.max(maxi, arr[i]);
mini = Math.min(mini, arr[i]);
}
let count = 0;
for (let i = 0; i < arr.length; i++) {
let temp_max = arr[i];
let temp_min = arr[i];
for (let j = i; j < arr.length; j++) {
if (arr[j] > temp_max) {
temp_max = arr[j];
}
if (arr[j] < temp_min) {
temp_min = arr[j];
}
// Checking that our subarray will contain
// maximum and minimum element of array
if (mini == temp_min && maxi == temp_max) {
count++;
}
}
}
return count;
}
// Driver Code
let arr = [4, 1, 2, 3];
// Function call
console.log(countSubArray(arr));
Output-
3
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: Follow the steps below to optimize the above approach:
- Find the index of the maximum and minimum elements. Let i and j be the respective indices such that i < j.
- All the subarray which starts from indices up to i and ends at indices after j will contain the maximum as well as the minimum array element.
- Therefore, the possible indices for the starting index of the subarray are [0, i] (total = i + 1 ).
- Therefore, the possible indices for the ending index of the subarray are [j, N - 1] (total = N - j).
- Therefore, the count of subarrays is given by (i + 1) * ( N - j).
Below is the implementation of the above approach:
C++
// 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;
}
Java
// 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
Python3
# 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
C#
// 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
JavaScript
<script>
// javascript program for the
// above approach
// Function to count subarray
// containing both maximum and
// minimum array elements
function countSubArray(arr, n)
{
// If the length of the
// array is less than 2
if (n < 2)
return n;
// Find the index of maximum element
let i = max_element(arr);
// Find the index of minimum element
let j = min_element(arr);
// If i > j, then swap
// the value of i and j
if (i > j)
{
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
// Return the answer
return (i + 1) * (n - j);
}
// Function to return max_element index
function max_element(arr)
{
let idx = 0;
let max = arr[0];
for(let i = 1; i < arr.length; i++)
{
if(max < arr[i])
{
max = arr[i];
idx = i;
}
}
return idx;
}
// Function to return min_element index
function min_element(arr)
{
let idx = 0;
let min = arr[0];
for(let i = 1; i < arr.length; i++)
{
if (arr[i] < min)
{
min = arr[i];
idx = i;
}
}
return idx;
}
// Driver Code
let arr = [ 4, 1, 2, 3 ];
let n = arr.length;
// Function call
document.write(countSubArray(arr, n));
// This code is contributed by avijitmondal1998
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Similar Reads
Count subsequences which contains both the maximum and minimum array element Given an array arr[] consisting of N integers, the task is to find the number of subsequences which contain the maximum as well as the minimum element present in the given array. Example : Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: There are 4 subsequence {1, 4}, {1, 2, 4}, {1, 3, 4}, {1, 2, 3
6 min read
Count subarrays for every array element in which they are the minimum Given an array arr[] consisting of N integers, the task is to create an array brr[] of size N where brr[i] represents the count of subarrays in which arr[i] is the smallest element. Examples: Input: arr[] = {3, 2, 4} Output: {1, 3, 1} Explanation: For arr[0], there is only one subarray in which 3 is
15+ min read
Maximize subarrays count containing the maximum and minimum Array element after deleting at most one element Given an array arr[] of size N. The task is to maximize the count of subarrays that contain both the minimum and maximum elements of the array by deleting at most one element from the array. Examples: Input: arr[] = {7, 2, 5, 4, 3, 1} Output: 4 Explanation: Delete 1 from the array then resultant arr
11 min read
Count subarrays for every array element in which they are the minimum | Set 2 Given an array arr[] consisting of N integers, the task is to create an array brr[] of size N where brr[i] represents the count of subarrays in which arr[i] is the smallest element. Examples: Input: arr[] = {3, 2, 4}Output: {1, 3, 1}Explanation: For arr[0], there is only one subarray in which 3 is t
12 min read
Count of Subarrays whose first element is the minimum Given an array arr[] of size N, the task is to find the number of subarrays whose first element is not greater than other elements of the subarray. Examples: Input: arr = {1, 2, 1}Output: 5Explanation: All subarray are: {1}, {1, 2}, {1, 2, 1}, {2}, {2, 1}, {1}From above subarray the following meets
10 min read