Greedy Algorithm to find Minimum number of Coins

28 Sep, 2021
Given a value V, if we want to make a change for V Rs, and we have an infinite supply of each of the denominations in Indian currency, i.e., we have an infinite supply of { 1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, what is the minimum number of coins and/or notes needed to make the change?
Examples:  
Input: V = 70
Output: 2
We need a 50 Rs note and a 20 Rs note.

Input: V = 121
Output: 3
We need a 100 Rs note, a 20 Rs note and a 1 Rs coin.
Solution: Greedy Approach.Approach: A common intuition would be to take coins with greater value first. This can reduce the total number of coins needed. Start from the largest possible denomination and keep adding denominations while the remaining value is greater than 0. 
Algorithm:  
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Sort the array of coins in decreasing order.Initialize result as empty.Find the largest denomination that is smaller than current amount.Add found denomination to result. Subtract value of found denomination from amount.If amount becomes 0, then print result.Else repeat steps 3 and 4 for new value of V.
Sort the array of coins in decreasing order.
Initialize result as empty.
Find the largest denomination that is smaller than current amount.
Add found denomination to result. Subtract value of found denomination from amount.
If amount becomes 0, then print result.
Else repeat steps 3 and 4 for new value of V.
C++
C
Java
Python3
C#
Javascript
// C++ program to find minimum// number of denominations#include <bits/stdc++.h>using namespace std;  // All denominations of Indian Currencyint deno[] = { 1, 2, 5, 10, 20,               50, 100, 500, 1000 };int n = sizeof(deno) / sizeof(deno[0]);  void findMin(int V){    sort(deno, deno + n);      // Initialize result    vector<int> ans;      // Traverse through all denomination    for (int i = n - 1; i >= 0; i--) {          // Find denominations        while (V >= deno[i]) {            V -= deno[i];            ans.push_back(deno[i]);        }    }      // Print result    for (int i = 0; i < ans.size(); i++)        cout << ans[i] << " ";}  // Driver programint main(){    int n = 93;    cout << "Following is minimal"         << " number of change for " << n         << ": ";    findMin(n);    return 0;}
// C program to find minimum// number of denominations#include <stdio.h>#define COINS 9#define MAX 20  // All denominations of Indian Currencyint coins[COINS] = { 1, 2, 5, 10, 20,                     50, 100, 200, 2000 };  void findMin(int cost){    int coinList[MAX] = { 0 };    int i, k = 0;      for (i = COINS - 1; i >= 0; i--) {        while (cost >= coins[i]) {            cost -= coins[i];            // Add coin in the list            coinList[k++] = coins[i];        }    }      for (i = 0; i < k; i++) {        // Print        printf("%d ", coinList[i]);    }    return;}  int main(void){    // input value    int n = 93;      printf("Following is minimal number"           "of change for %d: ",           n);    findMin(n);    return 0;}// Code by Munish Bhardwaj
// Java program to find minimum// number of denominationsimport java.util.Vector;  class GFG {      // All denominations of Indian Currency     static int deno[] = {1, 2, 5, 10, 20,     50, 100, 500, 1000};    static int n = deno.length;      static void findMin(int V)    {        // Initialize result         Vector<Integer> ans = new Vector<>();          // Traverse through all denomination         for (int i = n - 1; i >= 0; i--)        {            // Find denominations             while (V >= deno[i])             {                V -= deno[i];                ans.add(deno[i]);            }        }          // Print result         for (int i = 0; i < ans.size(); i++)        {            System.out.print(                " " + ans.elementAt(i));        }    }      // Driver code     public static void main(String[] args)     {        int n = 93;        System.out.print(            "Following is minimal number "            +"of change for " + n + ": ");        findMin(n);    }}  // This code is contributed by 29AjayKumar
# Python3 program to find minimum # number of denominations  def findMin(V):          # All denominations of Indian Currency    deno = [1, 2, 5, 10, 20, 50,             100, 500, 1000]    n = len(deno)          # Initialize Result    ans = []      # Traverse through all denomination    i = n - 1    while(i >= 0):                  # Find denominations        while (V >= deno[i]):            V -= deno[i]            ans.append(deno[i])          i -= 1      # Print result    for i in range(len(ans)):        print(ans[i], end = " ")  # Driver Codeif __name__ == '__main__':    n = 93    print("Following is minimal number",          "of change for", n, ": ", end = "")    findMin(n)      # This code is contributed by# Surendra_Gangwar
// C# program to find minimum// number of denominationsusing System;using System.Collections.Generic;  class GFG{  // All denominations of Indian Currency static int []deno = { 1, 2, 5, 10, 20,                       50, 100, 500, 1000 };static int n = deno.Length;  static void findMin(int V){          // Initialize result     List<int> ans = new List<int>();      // Traverse through all denomination     for(int i = n - 1; i >= 0; i--)    {                  // Find denominations         while (V >= deno[i])         {            V -= deno[i];            ans.Add(deno[i]);        }    }      // Print result     for(int i = 0; i < ans.Count; i++)    {        Console.Write(" " + ans[i]);    }}  // Driver code public static void Main(String[] args) {    int n = 93;    Console.Write("Following is minimal number " +                  "of change for " + n + ": ");                        findMin(n);}}  // This code is contributed by gauravrajput1
<script>// Javascript program to find minimum// number of denominations  // All denominations of Indian Currencylet deno=[1, 2, 5, 10, 20,    50, 100, 500, 1000];let n = deno.length;  function findMin(V){    // Initialize result        let ans = [];           // Traverse through all denomination        for (let i = n - 1; i >= 0; i--)        {            // Find denominations            while (V >= deno[i])            {                V -= deno[i];                ans.push(deno[i]);            }        }           // Print result        for (let i = 0; i < ans.length; i++)        {            document.write(                " " + ans[i]);        }}  // Driver coden = 93;document.write("Following is minimal number "+"of change for " + n + ": ");findMin(n);    // This code is contributed by rag2127</script>
Output:  
Following is minimal number of change 
for 93: 50  20  20  2  1
Complexity Analysis: 
Time Complexity: O(V).
Auxiliary Space: O(V).
Note: The above approach may not work for all denominations. For example, it doesn’t work for denominations {9, 6, 5, 1} and V = 11. The above approach would print 9, 1 and 1. But we can use 2 denominations 5 and 6. For general input, below dynamic programming approach can be used: Find minimum number of coins that make a given value 
Thanks to Utkarsh for providing the above solution here.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
SURENDRA_GANGWAR
MunishBhardwaj
29AjayKumar
bidibaaz123
reddy_bhargava
GauravRajput1
aakashsaini19992014
rag2127
dp-coin-change
Greedy
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Policemen catch thieves
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
Dijkstra’s Algorithm for Adjacency List Representation | Greedy Algo-8
Difference between Prim's and Kruskal's algorithm for MST
Minimize the maximum difference between the heights
3 Different ways to print Fibonacci series in Java
Number of indices pair such that element pair sum from first Array is greater than second Array
Greedy approach vs Dynamic programming
Rearrange characters in a string such that no two adjacent are same
Find maximum meetings in one room