Minimize cost to empty a given string by removing characters alphabetically | Function to find the minimum cost required to remove each character of the string in alphabetical order ; Stores the frequency of characters of the string ; Iterate through the string ; Count the number of characters smaller than the present character ; If no smaller character precedes current character ; Increase the frequency of the current character ; Return the total cost ; Given string str ; Function call
def minSteps ( str , N ) : NEW_LINE INDENT cost = 0 NEW_LINE f = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_ele = ord ( str [ i ] ) - ord ( ' a ' ) NEW_LINE smaller = 0 NEW_LINE for j in range ( curr_ele + 1 ) : NEW_LINE INDENT if ( f [ j ] ) : NEW_LINE INDENT smaller += f [ j ] NEW_LINE DEDENT DEDENT if ( smaller == 0 ) : NEW_LINE INDENT cost += ( i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT cost += ( i - smaller + 1 ) NEW_LINE DEDENT f [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return cost NEW_LINE DEDENT str = " abcab " NEW_LINE N = len ( str ) NEW_LINE print ( minSteps ( str , N ) ) NEW_LINE