Minimize swaps required to maximize the count of elements replacing a greater element in an Array | Java Program to implement the above approach ; Function to find the minimum number of swaps required ; Stores the frequency of the array elements ; Stores maximum frequency ; Find the max frequency ; Update frequency ; Update maximum frequency ; Driver Code ; function call
import java . util . * ; class GFG { static int countSwaps ( int arr [ ] , int n ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; int max_frequency = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } max_frequency = Math . max ( max_frequency , mp . get ( arr [ i ] ) ) ; } return n - max_frequency ; } public static void main ( String [ ] args ) { int A [ ] = { 6 , 5 , 4 , 3 , 2 , 1 } ; System . out . print ( countSwaps ( A , 6 ) ) ; } }