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 ; Function to return max_element index ; Function to return min_element index ; Driver Code ; Function call
using System ; class GFG { static int countSubArray ( int [ ] arr , int n ) { if ( n < 2 ) return n ; int i = max_element ( arr ) ; int j = min_element ( arr ) ; if ( i > j ) { int tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; } return ( i + 1 ) * ( n - j ) ; } 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 ; } 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 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 1 , 2 , 3 } ; int n = arr . Length ; Console . WriteLine ( countSubArray ( arr , n ) ) ; } }