Minimize swaps required to maximize the count of elements replacing a greater element in an Array | C ++ Program to implement the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSwaps ( int A [ ] , int n ) { sort ( A , A + n ) ; int ind = 1 , res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ind < n and A [ ind ] == A [ i ] ) ind ++ ; if ( ind < n and A [ ind ] > A [ i ] ) { res ++ ; ind ++ ; } if ( ind >= n ) break ; } return res ; } int main ( ) { int A [ ] = { 4 , 3 , 3 , 2 , 5 } ; cout << countSwaps ( A , 5 ) ; return 0 ; }