Minimum adjacent swaps to move maximum and minimum to corners | Function that returns the minimum swaps ; Index of leftmost largest element ; Index of rightmost smallest element ; Driver Code
function solve ( a , n ) { let maxx = - 1 , minn = a [ 0 ] , l = 0 , r = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] > maxx ) { maxx = a [ i ] ; l = i ; } if ( a [ i ] <= minn ) { minn = a [ i ] ; r = i ; } } if ( r < l ) document . write ( l + ( n - r - 2 ) ) ; else document . write ( l + ( n - r - 1 ) ) ; } let a = [ 5 , 6 , 1 , 3 ] ; let n = a . length ; solve ( a , n ) ;