Minimize Cost to sort a String in Increasing Order of Frequencies of Characters | Javascript program to implement above approach ; For a single character ; Stores count of repetitions of a character ; If repeating character ; Otherwise ; Store frequency ; Reset count ; Insert the last character block ; Sort the frequencies ; Stores the minimum cost of all operations ; Store the absolute difference of i - th frequencies of ordered and unordered sequences ; Return the minimum cost ; Driver Code
function sortString ( S ) { let sorted = [ ] ; let original = [ ] ; let insert = false ; if ( S . length == 1 ) { document . write ( 0 + " " ) ; } let curr = 1 ; for ( let i = 0 ; i < ( S . length - 1 ) ; i ++ ) { if ( S [ i ] == S [ i + 1 ] ) { curr += 1 ; insert = false ; } else { sorted . push ( curr ) ; original . push ( curr ) ; curr = 1 ; insert = true ; } } if ( ( S [ S . length - 1 ] != S [ S . length - 2 ] ) insert == false ) { sorted . push ( curr ) ; original . push ( curr ) ; } sorted . sort ( function ( a , b ) { return a - b } ) ; let t_cost = 0 ; for ( let i = 0 ; i < sorted . length ; i ++ ) { t_cost += Math . abs ( sorted [ i ] - original [ i ] ) ; } return parseInt ( t_cost / 2 , 10 ) ; } let S = " " ; document . write ( sortString ( S ) ) ;