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
function countSubArray ( arr , n ) { if ( n < 2 ) return n ; let i = max_element ( arr ) ; let j = min_element ( arr ) ; if ( i > j ) { let tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; } return ( i + 1 ) * ( n - j ) ; } 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 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 ; } let arr = [ 4 , 1 , 2 , 3 ] ; let n = arr . length ; document . write ( countSubArray ( arr , n ) ) ;