Here's a way to think about the problem of changing coins, which can be useful if you like graph theory.
Suppose you have a chart defined as follows:
- For each unit of money (for example, a penny), there is one node from 0 to the value you are interested in (for example, 39 cents or something else.)
- There is one arc between any two nodes separated exactly by the value of the coin that you can use (for example, a node between 34 cents and 29 cents if you are allowed to use nickel.)
Now you can think of the problem of changing coins as the shortest problem of the path from your interest value to zero, because the number of coins will be exactly the same as the number of arcs in your path.
The algorithm does not use the terminology of graph theory, but it does basically the same thing: the outer loop covers all the "cents" (or nodes within the graph theory), and the inner loop varies along all arcs (values in coinValueList) from the current arc to the next arcs. Together, they seek the shortest path from zero to your value. (A value to zero, zero to a value, does not matter. Traditionally, we look down to zero.)
I just started to understand dynamic programming when I realized that many problems can be posed as problems with graphics. (Be careful though ... not all of them can. Some of them are hypergraphs, and some probably not even that, but that helped me a lot.)
Novak
source share