C/C++ Program for Greedy Algorithm to find Minimum number of Coins


A greedy algorithm is an algorithm used to find an optimal solution for the given problem. greedy algorithm works by finding locally optimal solutions ( optimal solution for a part of the problem) of each part so show the Global optimal solution could be found.

In this problem, we will use a greedy algorithm to find the minimum number of coins/ notes that could makeup to the given sum. For this we will take under consideration all the valid coins or notes i.e. denominations of { 1, 2, 5, 10, 20, 50 , 100, 200 , 500 ,2000 }. And we need to return the number of these coins/notes we will need to make up to the sum.

Let’s take a few examples to understand the context better −

Example 1 −

Input : 1231
Output : 7

Explanation − We will need two Rs 500 notes, two Rs 100 notes, one Rs 20 note, one Rs 10 note and one Re 1 coin. That sums to 2+2+1+1+1 = 7

Example 2 −

Input : 2150
Output : 3

Explanation − We will need one Rs 2000 note, one Rs 100 note, and one Rs 50 note.

To solve this problem using a greedy algorithm, we will find the which is the largest denomination that can be used. then we will subtract the largest denomination from the sum and again do the same process until the sum becomes zero.

Algorithm

Input: sum,
Initialise the coins = 0
Step 1: Find the largest denomination that can be used i.e. smaller than sum.
Step 2: Add denomination two coins and subtract it from the Sum
Step 3: Repeat step 2 until the sum becomes 0.
Step 4: Print each value in coins.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int notes[] = { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 };
int n = sizeof(notes) / sizeof(notes[0]);
void minchange(int sum){
   vector<int> coins;
   for (int i = n - 1; i >= 0; i--) {
      while (sum >= notes[i]) {
         sum -= notes[i];
         coins.push_back(notes[i]);
      }
   }
   for (int i = 0; i < coins.size(); i++)
      cout << coins[i] << "\t";
}
int main(){
   int n = 3253;
   cout << "The minimum number of coins/notes that sum up " << n << " is \t ";
   minchange(n);
   return 0;
}

Output

The minimum number of coins/notes that sum up 3253 is
2000 500 500 200 50 2 1

Updated on: 19-Sep-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements