The pseudocode:
MinNumCoins ← ∞
This states "Initialize MinNumCoins to an infinity".
Your equivalent code:
int minNumCoins;
This declares minNumCoins
, but leaves this uninitialized. This is not only not what the pseudocode states, but since the code subsequently uses the uninitialized variable, this results in undefined behavior.
There are two basic approaches to implement this pseudocode:
1) Use a second variable, that indicates whether the value has been set, or not. The intent of initializing a variable to infinity to is to find the smallest value that gets computed for it. On each attempt, a potential candidate value for MinNumCoins
gets computed, and if it's less than the current value of MinNumCoins
, the new value replaces it. MinNumCoins
ends up having the smallest value that gets computed for it.
By initializing the variable with a positive infinity, this has the effect of taking the first computed value for MinNumCoins
, and setting it (since the first computed value will always be less than infinity).
The replacement logic uses a second variable, a flag, to indicate whether the value has been set. If it is not, the value gets set no matter what it is; but if the variable has been set, the code compares it to the new computed value, as usual, and updates it if the computed value is less than the existing value.
2) The second approach is to initialize the variable to the highest possible value. There is no value for "infinity", that an int
can be set to. The closest candiate would be the highest maximum value an int
can possibly be set to. This would be:
#include <limits>
int MinNumCoins = std::numeric_limits<int>::max();
Whether this somewhat "hack" would be an acceptable solution for your problem, is something for you to decide.