Minimal Coin Problem(DP)
Problem Statement:
Given an amount of money n, (n >= 1) and a list of coins (the number of each type of coin is unlimited), what is the minimal number of coins whose total value is equal to the amount of money n?
Analysis:
This is a very classic dynamic programming problem, and we can use the strategy we discuss in the class to solve general dp problems to solve this problem. From class, we discuss that the strategy to solve dp problem is:
- Identify the recursive structure of the problem
- Select a good order for solving subproblems
- Save solution to each subproblem in memory
In this problem, we can identify that there is an optimal substructure. In order to get the minimal number of coins for value i, the number of coins to get value j (where j < i and we assume that j can be summed up by the coins given) must also be minimal, or there is a better alternative. We define F(i) as the minimal number of coins to add up to value i. Then we have this recurrence relationship
F(i) = min(F(i – coinValue(j)) + 1)
where i is the current value of money and i >= coinValue(j)
The base case is F(0) = 0, which is obvious because we don’t need any coin to achieve value 0. With regard to the order for solving subproblems, I chose to use bottom-up dp, in which I first solve the minimal number of coins needed to constitute the less value, and get the answer for the larger values from the previous results. Finally, after solving each subproblem, I store the result into the dp table for the later use.
Implementation:
Below is the snapshot of my Java implementation to solve minimal coin problem: