Minimize swaps required to place largest and smallest array elements at first and last array indices | Python 3 program for the above approach ; Function to find the minimum count of adjacent swaps to move largest and smallest element at the first and the last index of the array , respectively ; Stores the smallest array element ; Stores the smallest array element ; Stores the last occurrence of the smallest array element ; Stores the first occurrence of the largest array element ; Traverse the array arr [ ] ; If a [ i ] is less than min_element ; Update min_element ; Update min_ind ; If a [ i ] is greater than max_element ; Update max_element ; Update max_ind ; If max_ind is equal to min_ind ; Return 0 ; If max_ind is greater than min_ind ; Otherwise ; Driver Code ; Input ; Print the result
import sys NEW_LINE def minimumMoves ( a , n ) : NEW_LINE INDENT min_element = sys . maxsize NEW_LINE max_element = - sys . maxsize - 1 NEW_LINE min_ind = - 1 NEW_LINE max_ind = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] <= min_element ) : NEW_LINE INDENT min_element = a [ i ] NEW_LINE min_ind = i NEW_LINE DEDENT if ( a [ i ] > max_element ) : NEW_LINE INDENT max_element = a [ i ] NEW_LINE max_ind = i NEW_LINE DEDENT DEDENT if ( max_ind == min_ind ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( max_ind > min_ind ) : NEW_LINE INDENT return max_ind + ( n - min_ind - 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return max_ind + n - min_ind - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 35 , 46 , 17 , 23 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimumMoves ( arr , N ) ) NEW_LINE DEDENT