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
< ? php function minSubarray ( $ A , $ n ) { $ minValue = min ( $ A ) ; $ maxValue = max ( $ A ) ; $ pos_min = -1 ; $ pos_max = -1 ; $ ans = PHP_INT_MAX ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ A [ $ i ] == $ minValue ) $ pos_min = $ i ; if ( $ A [ $ i ] == $ maxValue ) $ pos_max = $ i ; if ( $ pos_max != -1 and $ pos_min != -1 ) $ ans = min ( $ ans , abs ( $ pos_min - $ pos_max ) + 1 ) ; } return $ ans ; } $ A = array ( 1 , 5 , 9 , 7 , 1 , 9 , 4 ) ; $ n = sizeof ( $ A ) ; echo minSubarray ( $ A , $ n ) ; ? >