Minimum cost to modify a string | Function to return the minimum cost ; Initialize result ; To store the frequency of characters of the string ; Update the frequencies of the characters of the string ; Loop to check all windows from a - z where window size is K ; Starting index of window ; Ending index of window ; Check if the string contains character ; Check if the character is on left side of window find the cost of modification for character add value to count calculate nearest distance of modification ; Check if the character is on right side of window find the cost of modification for character add value to count calculate nearest distance of modification ; Find the minimum of all costs for modifying the string ; Loop to check all windows Here window contains characters before z and after z of window size K ; Starting index of window ; Ending index of window ; Check if the string contains character ; If characters are outside window find the cost for modifying character add value to count ; Find the minimum of all costs for modifying the string ; Driver code
def minCost ( str1 , K ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE res = 999999999 NEW_LINE count = 0 NEW_LINE cnt = [ 0 for i in range ( 27 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ ord ( str1 [ i ] ) - ord ( ' a ' ) + 1 ] += 1 NEW_LINE DEDENT for i in range ( 1 , 26 - K + 1 , 1 ) : NEW_LINE INDENT a = i NEW_LINE b = i + K NEW_LINE count = 0 NEW_LINE for j in range ( 1 , 27 , 1 ) : NEW_LINE INDENT if ( cnt [ j ] > 0 ) : NEW_LINE INDENT if ( j >= a and j >= b ) : NEW_LINE INDENT count = count + ( min ( j - b , 25 - j + a + 1 ) ) * cnt [ j ] NEW_LINE DEDENT elif ( j <= a and j <= b ) : NEW_LINE INDENT count = count + ( min ( a - j , 25 + j - b + 1 ) ) * cnt [ j ] NEW_LINE DEDENT DEDENT DEDENT res = min ( res , count ) NEW_LINE DEDENT for i in range ( 26 - K + 1 , 27 , 1 ) : NEW_LINE INDENT a = i NEW_LINE b = ( i + K ) % 26 NEW_LINE count = 0 NEW_LINE for j in range ( 1 , 27 , 1 ) : NEW_LINE INDENT if ( cnt [ j ] > 0 ) : NEW_LINE INDENT if ( j >= b and j <= a ) : NEW_LINE INDENT count = count + ( min ( j - b , a - j ) ) * cnt [ j ] NEW_LINE DEDENT DEDENT DEDENT res = min ( res , count ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abcdefghi " NEW_LINE K = 2 NEW_LINE print ( minCost ( str1 , K ) ) NEW_LINE DEDENT