Last Updated: 9 Dec, 2021

Greedy Algorithm For Ninja And The Coins

Easy
Asked in companies
Flipkart limitedHuman Holdings

Problem statement

Ninja went to the toffee shop, and he purchased some toffies worth 'V' cents. Ninja has an unlimited supply of coins of 1, 2, 5, 10, 20, 50, 100, 500, and 1000 cents. Now Ninja wants to know the minimum number of coins he needs to pay to the shopkeeper.

Your task is to find the minimum number of coins Ninja needs to pay to the shopkeeper so as to pay 'V' cents to him.

Note: You have to solve this problem using the greedy approach.

Example:
Input: 'V' = 60
Output: 2

Ninja need to pay two coins only 50 + 10 = 60
Input Format :
The first line of input contains an integer 'T', denoting the number of test cases. 

Each test case will contain only one integer 'V' on a separate line.
Output format :
For each test case, print the minimum number of coins Ninja needs to pay to the shopkeeper.

Output for each test case will be printed in a separate line.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= ‘T’ <= 10
1 <= 'V' <= 10^5
Time Limit: 1sec

Approaches

01 Approach

Approach: We will first take coins with a greater value for this problem. This will reduce the total number of coins. We will start from the largest possible coin and keep adding coins till the remaining value is not zero.

 

Algorithm : 

  1. Initialize the vector 'coins' and push the following integers in it.
    • 1, 2, 5, 10, 20, 50, 100, 500, 1000
  2. Sort the 'coins'.
  3. Initialize the variable 'count' by 0.
  4. Loop over the 'coins' with the variable 'i' from the last position.
    • Run a while loop till 'V' >= 'coins[i]'.
      • Update 'V' with 'V - coins[i]'.
      • Increment the 'count'.
  5. Return 'count'.