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
def countSwaps ( A , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE ind , res = 1 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( ind < n and A [ ind ] == A [ i ] ) : NEW_LINE INDENT ind += 1 NEW_LINE DEDENT if ( ind < n and A [ ind ] > A [ i ] ) : NEW_LINE INDENT res += 1 NEW_LINE ind += 1 NEW_LINE DEDENT if ( ind >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT A = [ 4 , 3 , 3 , 2 , 5 ] NEW_LINE print ( countSwaps ( A , 5 ) ) NEW_LINE