 # Codeforces DP problem explanation

#1

I am fairly new to dp and practicing to get better. Can anyone explain this problem from codeforces educational round. There is an editorial but still I am not convinced with the intution. Can anyone help me explain it?

https://codeforces.com/contest/1096/problem/D

#2

Here we can memoize our solution in the DP array, let dp* be the cost of making the string easy the index till 1<=i<=N where ith character can be any character of “hard”.

If the ith character of our string is ‘h’ then dp* = dp[i-1] + cost*.

If the ith character of our string is ‘a’ then dp* = we have 2 options whether to take dp[i-1] i.e. cost of making string easy removing only character ‘h’ or second option is to add the current cost of ‘a’ to the previously calculated cost of ‘a’ i.e. dp[i-1] + cost*.

Similarly, If the ith character of our string is ‘r’ then dp* = we have 2 options whether to take dp[i-1] i.e. cost of making string easy removing only character ‘a’ or second option is to add the cost of ‘r’ to the previously calculated cost of ‘r’ i.e. dp[i-1] + cost*.

Similarly for ‘d’ we have dp* = minimum of dp[i-1] // Taking only cost till first i-1 index and having character ‘r’ or take dp[i-1] i.e. adding ‘d’ cost into in the previous calculated cost of ‘d’.

``````for(int i = 1; i <= n; i++){
for(int j = 0; j < 4; j++){
dp*[j] = dp[i-1][j];

if(arr* == 'h'){
dp* = dp[i-1] + cost*;
}
else if(arr* == 'a'){
dp* = min(dp[i-1], dp[i-1] + cost*);
}
else if(arr* == 'r'){
dp* = min(dp[i-1],dp[i-1] + cost*);
}
else if(arr* == 'd'){
dp* = min(dp[i-1],dp[i-1] + cost*);
}
}
}
dp[n]; //Answer to the problem``````