text: Minimize cost to convert given string into concatenation of equal substrings of length K | C # program for the above approach ; Function to find minimum cost to convert given string into string of K length same substring ; Stores length of string ; Stores the minimum cost ; Traverse left substring of k length ; Stores the frequency ; Stores minimum cost for sequence of S [ i ] % k indices ; Check for optimal character ; Find sum of distance ' a ' + ch from character S [ i ] % k indices ; Choose minimum cost for each index i ; Increment ans ; Print minimum cost to convert string ; Driver Code ; Given string S ; Function call
code: using System ; class GFG { static void minCost ( string s , int k ) { int n = s . Length ; int ans = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int [ ] a = new int [ 26 ] ; for ( int j = i ; j < n ; j += k ) { a [ s [ j ] - ' a ' ] ++ ; } int min_cost = Int32 . MaxValue ; for ( int ch = 0 ; ch < 26 ; ch ++ ) { int cost = 0 ; for ( int tr = 0 ; tr < 26 ; tr ++ ) cost += Math . Abs ( ch - tr ) * a [ tr ] ; min_cost = Math . Min ( min_cost , cost ) ; } ans += min_cost ; } Console . WriteLine ( ans ) ; } public static void Main ( ) { string S = " abcdefabc " ; int K = 3 ; minCost ( S , K ) ; } }