Minimize cost to convert given string into concatenation of equal substrings of length K | Java 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
import java . util . * ; import java . lang . * ; 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 . charAt ( j ) - ' a ' ] ++ ; } int min_cost = Integer . MAX_VALUE ; 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 ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S = " abcdefabc " ; int K = 3 ; minCost ( S , K ) ; } }