Changing Money Using Dynamic Programming
Let’s use a dynamic programming approach to solve the Change Problem.
We'll cover the following
To avoid the many recursive calls that are needed to compute MinNumCoins(money), we’ll use a dynamic programming strategy. Wouldn’t it be nice to know all the values of MinNumCoins(money − coin) by the time we compute MinNumCoins(money)? Instead of the time-consuming calls to RecursiveChange(money − coin, Coins), we could simply look up the values of MinNumCoins(money − coin) in an array and thus compute MinNumCoins(money) using just |Coins| comparisons.
The key to dynamic programming is to take a step that may seem counterintuitive. Instead of computing MinNumCoins(m) for every value of m from 76 downward toward m = 1 via recursive calls, we’ll invert our thinking and compute MinNumCoins(m) from m = 1 upward toward 76, storing all these values in an array so that we only need to compute MinNumCoins(m) once for each value of m. MinNumCoins(m) is still computed via the same recurrence relation:
For example, assuming that we’ve already computed MinNumCoins(m) for ,
Following the same reasoning,
Continuing these calculations results in the figure below.
Get hands-on with 1200+ tech skills courses.