Minimize swaps required to maximize the count of elements replacing a greater element in an Array | Function to find the minimum number of swaps required ; Sort the array in ascending order ; Iterate until a greater element is found ; Keep incrementing ind ; If a greater element is found ; Increase count of swap ; Increment ind ; If end of array is reached ; Return the answer ; Driver Code
function countSwaps ( A , n ) { A . sort ( ) ; let ind = 1 , res = 0 ; for ( let i = 0 ; i < n ; i ++ ) { while ( ind < n && A [ ind ] == A [ i ] ) ind ++ ; if ( ind < n && A [ ind ] > A [ i ] ) { res ++ ; ind ++ ; } if ( ind >= n ) break ; } return res ; } let A = [ 4 , 3 , 3 , 2 , 5 ] ; document . write ( countSwaps ( A , 5 ) ) ;