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: #include <bits/stdc++.h> NEW_LINE using namespace std ; void minCost ( string s , int k ) { int n = s . size ( ) ; int ans = 0 ; for ( int i = 0 ; i < k ; i ++ ) { int a [ 26 ] ; for ( int p = 0 ; p < 26 ; p ++ ) { a [ p ] = 0 ; } for ( int j = i ; j < n ; j += k ) { a [ s [ j ] - ' a ' ] ++ ; } int min_cost = INT_MAX ; for ( int ch = 0 ; ch < 26 ; ch ++ ) { int cost = 0 ; for ( int tr = 0 ; tr < 26 ; tr ++ ) cost += abs ( ch - tr ) * a [ tr ] ; min_cost = min ( min_cost , cost ) ; } ans += min_cost ; } cout << ( ans ) ; } int main ( ) { string S = " abcdefabc " ; int K = 3 ; minCost ( S , K ) ; }