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
function minSteps ( str , N ) { var smaller , cost = 0 ; var f = new Array ( 26 ) . fill ( 0 ) ; for ( var i = 0 ; i < N ; i ++ ) { var curr_ele = str [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ; smaller = 0 ; for ( var j = 0 ; j <= curr_ele ; j ++ ) { if ( f [ j ] !== 0 ) smaller += f [ j ] ; } if ( smaller === 0 ) cost += i + 1 ; else cost += i - smaller + 1 ; f [ str [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ++ ; } return cost ; } var str = " " ; var N = str . length ; document . write ( minSteps ( str , N ) ) ;