Recursive code of coin exchange problem

By adding another variable to calculate return ans the code will work, but I don’t understand the need for it.
this is my code:

Like this is my recursive code for wines problem , in this if I rather initialising ans I return k the code works. So can you please explain when to initialise another variable and when don’t.

I cannot understand your doubt.
Here fo and ba are not needed to be initialized, because any how they will hold some value(after recursive calls). There will not be any case where fo or bo will hold garbage value.

why this code is giving wrong ans?

ignore the output.txt, output is 1 as in terminal.

k must be initialized just before the loop. Because it must be reinitialized to INT_MAX for each problem.
k will store the minm number of coins to reach amount n. After the first recursive call, n is reduced to n-coins[i], now to compute the minm number of coins for this subproblem, you should again reinitialize k to INT_MAX.
Refer the correct recursive approach from here

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.