Smallest subarray containing minimum and maximum values | Function to return length of smallest subarray containing both maximum and minimum value ; find maximum and minimum values in the array ; iterate over the array and set answer to smallest difference between position of maximum and position of minimum value ; last occurrence of minValue ; last occurrence of maxValue ; Driver code
function minSubarray ( A , n ) { let minValue = Number . MAX_VALUE ; let maxValue = Number . MIN_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { minValue = Math . min ( minValue , A [ i ] ) ; maxValue = Math . max ( maxValue , A [ i ] ) ; } let pos_min = - 1 , pos_max = - 1 , ans = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { if ( A [ i ] == minValue ) pos_min = i ; if ( A [ i ] == maxValue ) pos_max = i ; if ( pos_max != - 1 && pos_min != - 1 ) ans = Math . min ( ans , Math . abs ( pos_min - pos_max ) + 1 ) ; } return ans ; } let A = [ 1 , 5 , 9 , 7 , 1 , 9 , 4 ] ; let n = A . length ; document . write ( minSubarray ( A , n ) ) ;