Minimum cost to make a string free of a subsequence | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCost ( string str , int arr [ ] , int n ) { long long costofC = 0 , costofO = 0 , costofD = 0 , costofE = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' c ' ) costofC += arr [ i ] ; else if ( str [ i ] == ' o ' ) costofO = min ( costofC , costofO + arr [ i ] ) ; else if ( str [ i ] == ' d ' ) costofD = min ( costofO , costofD + arr [ i ] ) ; else if ( str [ i ] == ' e ' ) costofE = min ( costofD , costofE + arr [ i ] ) ; } return costofE ; } int main ( ) { string str = " geekcodergeeks " ; int arr [ ] = { 1 , 2 , 1 , 3 , 4 , 2 , 6 , 4 , 6 , 2 , 3 , 3 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCost ( str , arr , n ) ; return 0 ; }