Count subarrays which contains both the maximum and minimum array element | ''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
def countSubArray ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT i = max_element ( arr ) ; NEW_LINE j = min_element ( arr ) ; NEW_LINE if ( i > j ) : NEW_LINE INDENT tmp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = tmp ; NEW_LINE DEDENT return ( i + 1 ) * ( n - j ) ; NEW_LINE DEDENT def max_element ( arr ) : NEW_LINE INDENT idx = 0 ; NEW_LINE max = arr [ 0 ] ; NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE idx = i ; NEW_LINE DEDENT DEDENT return idx ; NEW_LINE DEDENT def min_element ( arr ) : NEW_LINE INDENT idx = 0 ; NEW_LINE min = arr [ 0 ] ; NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] ; NEW_LINE idx = i ; NEW_LINE DEDENT DEDENT return idx ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countSubArray ( arr , n ) ) ; NEW_LINE DEDENT