Smallest subarray containing minimum and maximum values | Python3 implementation of above approach ; 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
import sys NEW_LINE def minSubarray ( A , n ) : NEW_LINE INDENT minValue = min ( A ) NEW_LINE maxValue = max ( A ) NEW_LINE pos_min , pos_max , ans = - 1 , - 1 , sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] == minValue : NEW_LINE INDENT pos_min = i NEW_LINE DEDENT if A [ i ] == maxValue : NEW_LINE INDENT pos_max = i NEW_LINE DEDENT if pos_max != - 1 and pos_min != - 1 : NEW_LINE INDENT ans = min ( ans , abs ( pos_min - pos_max ) + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 1 , 5 , 9 , 7 , 1 , 9 , 4 ] NEW_LINE n = len ( A ) NEW_LINE print ( minSubarray ( A , n ) ) NEW_LINE