Minimize cost to convert given string into concatenation of equal substrings of length K | Python3 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 ; Given string S ; Function call
import sys NEW_LINE def minCost ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT a = [ 0 ] * 26 NEW_LINE for j in range ( i , n , k ) : NEW_LINE INDENT a [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT min_cost = sys . maxsize - 1 NEW_LINE for ch in range ( 26 ) : NEW_LINE INDENT cost = 0 NEW_LINE for tr in range ( 26 ) : NEW_LINE INDENT cost += abs ( ch - tr ) * a [ tr ] NEW_LINE DEDENT min_cost = min ( min_cost , cost ) NEW_LINE DEDENT ans += min_cost NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = " abcdefabc " NEW_LINE K = 3 NEW_LINE minCost ( S , K ) NEW_LINE