Activity: The Coin Change Problem

Scenario

In this activity, we will be building a dynamic programming algorithm to solve the coin change problem. Given a value, N, if we want to split it into coins, and we have an infinite supply of each of S={S1, S2, …, Sm} valued coins, in how many ways can we do it? The order of the coins doesn't matter. For N = 4 and S = {1, 2, 3}, there are four solutions: {1, 1, 1, 1}, {1, 1, 2}, {2, 2}, and {1, 3}, so the result should be four.

Aim

To solve the coin change problem as described previously using a dynamic programming algorithm.

Prerequisites

You need to implement the ways() method of the CoinChange class, which returns the number of ways to produce a given change for amount N, given a set of coins. It is available on the following path:

https://github.com/TrainingByPackt/Data-Structures-and-Algorithms-in-Java/blob/master/src/main/java/com/packt/datastructuresandalg/lesson4/activity/coinchange/CoinChange.java.


The source code comes with a test suite for this class, so to verify that your solution is correct, run ./gradlew test in the command line.

Steps for Completion

  1. When going through a coin Sm, in order to count the number of solutions, we can divide the solution into two sets:
    • Those that do not contain any coin Sm
    • Those that contain at least one Sm
  2. If w[i][j] counts the number of ways to make change for i using coins up to Sj, then we have the following recursion:

In this third and final section, we introduced the dynamic programming paradigm of algorithm design, using the 0-1 knapsack and the longest common subsequence problems as examples. We introduced the two properties a problem must observe to be optimally solved by a dynamic programming algorithm: optimal substructure and overlapping subproblems, and showed the students how to identify these properties. We've also seen the differences between a top-down (with memoization) and a bottom-up approach in dynamic programming algorithms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset