Minimize cost to empty a given string by removing characters alphabetically | Java program for the above approach ; 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 ; Driver Code ; Given string str ; Function call
import java . io . * ; class GFG { static int minSteps ( String str , int N ) { int smaller , cost = 0 ; int f [ ] = new int [ 26 ] ; for ( int i = 0 ; i < N ; i ++ ) { int curr_ele = str . charAt ( i ) - ' a ' ; smaller = 0 ; for ( int 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 . charAt ( i ) - ' a ' ] ++ ; } return cost ; } public static void main ( String [ ] args ) { String str = " abcab " ; int N = str . length ( ) ; System . out . println ( minSteps ( str , N ) ) ; } }