Minimize swaps required to make the first and last elements the largest and smallest elements in the array respectively | Function to find the minimum number of swaps required to make the first and the last elements the largest and smallest element in the array ; Stores the count of swaps ; Stores the maximum element ; Stores the minimum element ; If the array contains a single distinct element ; Stores the indices of the maximum and minimum elements ; If the first index of the maximum element is found ; If current index has the minimum element ; Update the count of operations to place largest element at the first ; Update the count of operations to place largest element at the last ; If smallest element is present before the largest element initially ; Driver Code
def minimum_swaps ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE max_el = max ( arr ) NEW_LINE min_el = min ( arr ) NEW_LINE if ( min_el == max_el ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT index_max = - 1 NEW_LINE index_min = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == max_el and index_max == - 1 ) : NEW_LINE INDENT index_max = i NEW_LINE DEDENT if ( arr [ i ] == min_el ) : NEW_LINE INDENT index_min = i NEW_LINE DEDENT DEDENT count += index_max NEW_LINE count += ( n - 1 - index_min ) NEW_LINE if ( index_min < index_max ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimum_swaps ( arr , N ) ) NEW_LINE DEDENT