text: Minimum cost to remove the spaces between characters of a String by rearranging the characters | Java 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
code: import java . util . * ; import java . lang . * ; class GFG { static int min_cost ( String S ) { int cost = 0 ; int F = 0 ; int B = 0 ; int count = 0 ; for ( char c : S . toCharArray ( ) ) if ( c == ' ▁ ' ) count ++ ; int n = S . length ( ) - count ; if ( n == 1 ) return cost ; for ( char in : S . toCharArray ( ) ) { if ( in != ' ▁ ' ) { 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 $ " ; System . out . println ( min_cost ( S ) ) ; } }