Minimize swaps required to place largest and smallest array elements at first and last array indices | 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 ; Input ; Prlet the result
function minimumMoves ( a , n ) { let min_element = Number . MAX_VALUE ; let max_element = Number . MIN_VALUE ; let min_ind = - 1 ; let max_ind = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] <= min_element ) { min_element = a [ i ] ; min_ind = i ; } if ( a [ i ] > max_element ) { max_element = a [ i ] ; max_ind = i ; } } if ( max_ind == min_ind ) { return 0 ; } else if ( max_ind > min_ind ) { return max_ind + ( n - min_ind - 2 ) ; } else { return max_ind + n - min_ind - 1 ; } } let arr = [ 35 , 46 , 17 , 23 ] ; let N = arr . length ; document . write ( minimumMoves ( arr , N ) + " " ) ;