text: Minimize cost to convert given string into concatenation of equal substrings of length K | 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
code: function minCost ( s , k ) { var n = s . length ; var ans = 0 ; for ( var i = 0 ; i < k ; i ++ ) { var a = new Array ( 26 ) . fill ( 0 ) ; for ( var j = i ; j < n ; j += k ) { a [ s [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } var min_cost = 1000000000 ; for ( var ch = 0 ; ch < 26 ; ch ++ ) { var cost = 0 ; for ( var tr = 0 ; tr < 26 ; tr ++ ) cost += Math . abs ( ch - tr ) * a [ tr ] ; min_cost = Math . min ( min_cost , cost ) ; } ans += min_cost ; } document . write ( ans ) ; } var S = " " ; var K = 3 ; minCost ( S , K ) ;