Minimum cost to make a string free of a subsequence | Java implementation of the approach ; Function to return the minimum cost ; Traverse the string ; Min Cost to remove ' c ' ; Min Cost to remove subsequence " co " ; Min Cost to remove subsequence " cod " ; Min Cost to remove subsequence " code " ; Return the minimum cost ; Driver program
class GFG { static int findCost ( String str , int arr [ ] , int n ) { long costofC = 0 , costofO = 0 , costofD = 0 , costofE = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' c ' ) costofC += arr [ i ] ; else if ( str . charAt ( i ) == ' o ' ) costofO = Math . min ( costofC , costofO + arr [ i ] ) ; else if ( str . charAt ( i ) == ' d ' ) costofD = Math . min ( costofO , costofD + arr [ i ] ) ; else if ( str . charAt ( i ) == ' e ' ) costofE = Math . min ( costofD , costofE + arr [ i ] ) ; } return ( int ) costofE ; } public static void main ( String [ ] args ) { String str = " geekcodergeeks " ; int arr [ ] = { 1 , 2 , 1 , 3 , 4 , 2 , 6 , 4 , 6 , 2 , 3 , 3 , 3 , 2 } ; int n = arr . length ; System . out . print ( findCost ( str , arr , n ) ) ; } }