Minimum cost to remove the spaces between characters of a String by rearranging the characters | C # program to gather characters of a string in minimum cost ; 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
using System ; class GFG { static int min_cost ( String S ) { int cost = 0 ; int F = 0 ; int B = 0 ; int count = 0 ; foreach ( char c in S . ToCharArray ( ) ) if ( c == ' ▁ ' ) count ++ ; int n = S . Length - count ; if ( n == 1 ) return cost ; foreach ( char inn in S . ToCharArray ( ) ) { if ( inn != ' ▁ ' ) { if ( B != 0 ) { cost += Math . Min ( n - F , F ) * B ; B = 0 ; } F += 1 ; } else { B += 1 ; } } return cost ; } public static void Main ( String [ ] args ) { String S = " ▁ @ TABSYMBOL $ " ; Console . WriteLine ( min_cost ( S ) ) ; } }