text: Minimize cost of removals required to make all remaining characters of the string unique | Java program to implement the above approach ; Function to find the minimum cost of removing characters to make the string unique ; stores the visited character ; stores the answer ; traverse the string ; if already visited ; Stores the maximum cost of removing a particular character ; Store the total deletion cost of a particular character ; Mark the current character visited ; Traverse the indices of the string [ i , N - 1 ] ; If any duplicate is found ; Update the maximum cost and total cost ; Mark the current character visited ; Keep the character with maximum cost and delete the rest ; return the minimum cost ; Driver code ; input string ; input array ; function call
code: import java . io . * ; class GFG { public static int delCost ( String s , int [ ] cost ) { boolean visited [ ] = new boolean [ s . length ( ) ] ; int ans = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( visited [ i ] ) { continue ; } int maxDel = 0 ; int totalCost = 0 ; visited [ i ] = true ; for ( int j = i ; j < s . length ( ) ; j ++ ) { if ( s . charAt ( i ) == s . charAt ( j ) ) { maxDel = Math . max ( maxDel , cost [ j ] ) ; totalCost += cost [ j ] ; visited [ j ] = true ; } } ans += totalCost - maxDel ; } 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 ) ) ; } }