Minimum distance between the maximum and minimum element of a given Array | Python3 Program to implement the above approach ; Function to find the minimum distance between the minimum and the maximum element ; Stores the minimum and maximum array element ; Stores the most recently traversed indices of the minimum and the maximum element ; Stores the minimum distance between the minimum and the maximium ; Find the maximum and the minimum element from the given array ; Find the minimum distance ; Check if current element is equal to minimum ; Check if current element is equal to maximum ; If both the minimum and the maximum element has occurred at least once ; Driver Code
import sys NEW_LINE def minDistance ( a , n ) : NEW_LINE INDENT maximum = - 1 NEW_LINE minimum = sys . maxsize NEW_LINE min_index = - 1 NEW_LINE max_index = - 1 NEW_LINE min_dist = n + 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > maximum ) : NEW_LINE INDENT maximum = a [ i ] NEW_LINE DEDENT if ( a [ i ] < minimum ) : NEW_LINE INDENT minimum = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == minimum ) : NEW_LINE INDENT min_index = i NEW_LINE DEDENT if ( a [ i ] == maximum ) : NEW_LINE INDENT max_index = i NEW_LINE DEDENT if ( min_index != - 1 and max_index != - 1 ) : NEW_LINE INDENT min_dist = ( min ( min_dist , abs ( min_index - max_index ) ) ) NEW_LINE DEDENT DEDENT return min_dist NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 8 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( minDistance ( a , n ) ) NEW_LINE DEDENT