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