text: Minimum operations to make frequency of all characters equal K | C # program to convert the given string ; Function to find the minimum number of operations to convert the given string ; Check if N is divisible by K ; Array to store frequency of characters in given string ; Two arrays with number of operations required ; Checking for all possibility ; Driver Code
code: using System ; using System . Collections . Generic ; class GFG { static void minOperation ( string S , int N , int K ) { if ( N % K != 0 ) { Console . WriteLine ( " Not ▁ Possible " ) ; } else { int [ ] count = new int [ 26 ] ; for ( int i = 0 ; i < N ; i ++ ) { count [ ( S [ i ] - 97 ) ] ++ ; } int E = N / K ; List < int > greaterE = new List < int > ( ) ; List < int > lessE = new List < int > ( ) ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( count [ i ] < E ) lessE . Add ( E - count [ i ] ) ; else greaterE . Add ( count [ i ] - E ) ; } greaterE . Sort ( ) ; lessE . Sort ( ) ; int mi = Int32 . MaxValue ; for ( int i = 0 ; i <= K ; i ++ ) { int set1 = i ; int set2 = K - i ; if ( greaterE . Count >= set1 && lessE . Count >= set2 ) { int step1 = 0 ; int step2 = 0 ; for ( int j = 0 ; j < set1 ; j ++ ) step1 += greaterE [ j ] ; for ( int j = 0 ; j < set2 ; j ++ ) step2 += lessE [ j ] ; mi = Math . Min ( mi , Math . Max ( step1 , step2 ) ) ; } } Console . WriteLine ( mi ) ; } } public static void Main ( ) { string S = " accb " ; int N = S . Length ; int K = 2 ; minOperation ( S , N , K ) ; } }