Find Minimum Number Of Coins

Posted: 9 Dec, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

Dora, the explorer, visits India and decides to try the famous Indian food. However, the restaurant accepts only Indian currency i.e. [1, 2, 5, 10, 20, 50, 100, 500, 1000] valued coins.

So, Dora goes to a bank that has an infinite supply of each of the denominations to make a change for a given ‘Amount’ of money. As a cashier at the bank, your task is to provide Dora the minimum number of coins that add up to the given ‘Amount’.

For Example
For Amount = 70, the minimum number of coins required is 2 i.e an Rs. 50 coin and a Rs. 20 coin.
Note
It is always possible to find the minimum number of coins for the given amount. So, the answer will always exist.
Input Format
The first line of input contains an integer 'T' representing the number of test cases or queries to be processed. Then the test case follows.

The only line of each test case contains a single integer ‘Amount’ representing the amount Dora wishes to change to Indian currency.
Output Format
For each test case, print the minimum number of coins needed to make the change.

Print the output of each test case in a separate line.
Note
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints
1 <= T <= 100
1 <= Amount <= 10^5
Where 'T' is the number of test-cases
Time Limit: 1sec
Approach 1

We can use dynamic programming to solve this problem. 

 

We maintain a vector ‘dp’ of size AMOUNT+1 and initialize it to a maximum value (say AMOUNT + 1). Here, dp[i] stores the minimum number of coins needed to change an amount ‘i’. 

 

Algorithm

 

  • We set dp[0] to 0 as minimum coins to change an amount of ‘0’ is 0.
  • We then traverse denominations from beginning to end (loop variable i).
    • We loop from denominations[i] to amount (loop variable j).
      • Now, if we pick the i-th coin, we will be interested in minimum coins needed to make a change of amount j - denominations[i].
      • So, we set dp[j] to the minimum of dp[j] and dp[j - denominations[i]] + 1.
  • Finally, we return dp[amount] as answer.
Try Problem