text: 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
code: function min_cost ( S ) { let cost = 0 ; let F = 0 ; let B = 0 ; let count = 0 ; for ( let i in S ) if ( S [ i ] == ' ' ) count ++ ; let n = S . length - count ; if ( n == 1 ) return cost ; for ( let i in S ) { if ( S [ i ] != ' ' ) { if ( B != 0 ) { cost += Math . min ( n - F , F ) * B ; B = 0 ; } F += 1 ; } else { B += 1 ; } } return cost ; } let S = " " ; document . write ( min_cost ( S . split ( ' ' ) ) ) ;