Minimum cost to remove the spaces between characters of a String by rearranging the characters | Function to calculate the minimum cost ; Stores the minimum cost ; Stores the count of characters found ; Stores the count of blank spaces found ; Stores the count of total characters ; If the count of characters is equal to 1 ; Iterate over the string ; Consider the previous character together with current character ; If not together already ; Add the cost to group them together ; Increase count of characters found ; Otherwise ; Increase count of spaces found ; Return the total cost obtained ; Driver Code
def min_cost ( S ) : NEW_LINE INDENT cost = 0 NEW_LINE F = 0 NEW_LINE B = 0 NEW_LINE n = len ( S ) - S . count ( ' ▁ ' ) NEW_LINE if n == 1 : NEW_LINE INDENT return cost NEW_LINE DEDENT for char in S : NEW_LINE INDENT if char != ' ▁ ' : NEW_LINE INDENT if B != 0 : NEW_LINE INDENT cost += min ( n - F , F ) * B NEW_LINE B = 0 NEW_LINE DEDENT F += 1 NEW_LINE DEDENT else : NEW_LINE INDENT B += 1 NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT S = " ▁ @ TABSYMBOL $ " NEW_LINE print ( min_cost ( S ) ) NEW_LINE