Minimize Cost to sort a String in Increasing Order of Frequencies of Characters | Python3 program to implement the 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
def sortString ( S ) : NEW_LINE INDENT sorted1 = [ ] NEW_LINE original = [ ] NEW_LINE insert = False NEW_LINE if ( len ( S ) == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT curr = 1 NEW_LINE for i in range ( len ( S ) - 1 ) : NEW_LINE INDENT if ( S [ i ] == S [ i + 1 ] ) : NEW_LINE INDENT curr += 1 NEW_LINE insert = False NEW_LINE DEDENT else : NEW_LINE INDENT sorted1 . append ( curr ) NEW_LINE original . append ( curr ) NEW_LINE curr = 1 NEW_LINE insert = True NEW_LINE DEDENT DEDENT if ( ( S [ ( len ( S ) - 1 ) ] != S [ ( len ( S ) - 2 ) ] ) or insert == False ) : NEW_LINE INDENT sorted1 . append ( curr ) NEW_LINE original . append ( curr ) NEW_LINE DEDENT sorted1 . sort ( ) NEW_LINE t_cost = 0 NEW_LINE for i in range ( len ( sorted1 ) ) : NEW_LINE INDENT t_cost += abs ( sorted1 [ i ] - original [ i ] ) NEW_LINE DEDENT return ( t_cost // 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aabbcccdeffffggghhhhhii " NEW_LINE print ( sortString ( S ) ) NEW_LINE DEDENT