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
function minimum_swaps ( arr , n ) { var count = 0 ; var max_el = Math . max ( ... arr ) ; var min_el = Math . min ( ... arr ) ; if ( min_el === max_el ) return 0 ; var index_max = - 1 ; var index_min = - 1 ; for ( var i = 0 ; i < n ; i ++ ) { if ( arr [ i ] === max_el && index_max === - 1 ) { index_max = i ; } if ( arr [ i ] === min_el ) { index_min = i ; } } count += index_max ; count += n - 1 - index_min ; if ( index_min < index_max ) count -= 1 ; return count ; } var arr = [ 2 , 4 , 1 , 6 , 5 ] ; var N = arr . length ; document . write ( minimum_swaps ( arr , N ) ) ;