We want to purchase an item of price and for that, we have an unlimited (!) supply of three types of coins with values 5, 9, and 13, respectively. Our goal is to purchase this item using the smallest possible number of coins or outputting that this is simply not possible. Design a dynamic programming algorithm for this problem with the worst-case runtime ofO(n). Example. A couple of examples for this problem: •Givenn= 17, the answer is “not possible” (try it!). •Givenn= 18, the answer is 2 coins: we pick 2 coins of value 9 (or 1 coin of value 5 and 1 of value 13). •Givenn= 19, the answer is 3 coins: we pick 1 coin of value 9 and 2 coins of value 5. •Givenn= 20, the answer is 4 coins: we pick 4 coins of value 5. •Givenn= 21, the answer is “not possible” (try it!). •Givenn= 22, the answer is 2 coins: we pick 1 coin of value 13 and 1 coin of value 9. •Givenn= 23, the answer is 3 coins: we pick 1 coin of value 13 and 2 coins of value 5. Please explain it too! Thanks!
We want to purchase an item of price and for that, we have an unlimited (!) supply of three types of coins with values 5, 9, and 13, respectively. Our goal is to purchase this item using the smallest possible number of coins or outputting that this is simply not possible. Design a dynamic
Example. A couple of examples for this problem:
•Givenn= 17, the answer is “not possible” (try it!).
•Givenn= 18, the answer is 2 coins: we pick 2 coins of value 9 (or 1 coin of value 5 and 1 of value 13).
•Givenn= 19, the answer is 3 coins: we pick 1 coin of value 9 and 2 coins of value 5.
•Givenn= 20, the answer is 4 coins: we pick 4 coins of value 5.
•Givenn= 21, the answer is “not possible” (try it!).
•Givenn= 22, the answer is 2 coins: we pick 1 coin of value 13 and 1 coin of value 9.
•Givenn= 23, the answer is 3 coins: we pick 1 coin of value 13 and 2 coins of value 5.
Please explain it too! Thanks!
The dynamic programming algorithm for problem 4 will be:
1. We will make a 1-D dp array where dp[i] represents the minimum number of coins required to make i. We will make dp[i]= INT_MAX if it is not possible to make i using the given coins.
2. We have 3 options to make i: (a) if (i >=5) dp[i] = min(dp[i], dp[i-5] + 1). (b) if(i>=9) dp[i] = min(dp[i], dp[i-9] + 1), (c) if(i>=13) dp[i] = min(dp[i], dp[i-13] + 1). Here is the pseudocode:
long int dp[n+1];
dp[0]=0; //this is the base case, there are no coins required to make 0
for int i=1 to n //filling the dp array
dp[i]=INT_MAX
Trending now
This is a popular solution!
Step by step
Solved in 2 steps