text: Minimize cost of removals required to make all remaining characters of the string unique | Java program for the above approach ; Function to find the minimum cost of removing characters to make the string unique ; Store the minimum cost required ; Create a dictionary to store the maximum cost of removal a character ; Create a dictionary to store the total deletion cost of a character ; Traverse the string , S ; Keep track of maximum cost of each character ; Update the maximum deletion cost ; Keep track of the total cost of each character ; Update the total deletion cost ; Traverse through all the unique characters ; Keep the maximum cost character and delete the rest ; Return the answer ; Driver code ; Given string ; Given cost array ; Function Call
code: import java . util . * ; public class GFG { static int delCost ( String s , int [ ] cost ) { int ans = 0 ; HashMap < Character , Integer > forMax = new HashMap < > ( ) ; HashMap < Character , Integer > forTot = new HashMap < > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! forMax . containsKey ( s . charAt ( i ) ) ) { forMax . put ( s . charAt ( i ) , cost [ i ] ) ; } else { forMax . put ( s . charAt ( i ) , Math . max ( cost [ i ] , forMax . get ( s . charAt ( i ) ) ) ) ; } if ( ! forTot . containsKey ( s . charAt ( i ) ) ) { forTot . put ( s . charAt ( i ) , cost [ i ] ) ; } else { forTot . put ( s . charAt ( i ) , forTot . get ( s . charAt ( i ) ) + cost [ i ] ) ; } } for ( Map . Entry < Character , Integer > i : forMax . entrySet ( ) ) { ans += forTot . get ( i . getKey ( ) ) - i . getValue ( ) ; } return ans ; } public static void main ( String [ ] args ) { String s = " AAABBB " ; int [ ] cost = { 1 , 2 , 3 , 4 , 5 , 6 } ; System . out . println ( delCost ( s , cost ) ) ; } }