Minimum number of coins that make a given value


There is a list of coin C(c1, c2, ……Cn) is given and a value V is also given. Now the problem is to use the minimum number of coins to make the chance V.

Note: Assume there is the infinite number of coins C.

In this problem, we will consider a set of different coins C{1, 2, 5, 10} are given, There is the infinite number of coins of each type. To make change the requested value we will try to take the minimum number of coins of any type. As an example, for value 22: we will choose {10, 10, 2}, 3 coins as the minimum.

Input and Output

Input:
The required value. Say 48
Output:
Minimum required coins. Here the output is 7.
48 = 10 + 10 + 10 + 10 + 5 + 2 + 1

Algorithm

minCoins(coinList, n, value)

Input: list of different coins, number of coins, given value.

Output: Minimum number of coins to get given value.

Begin
   if value = 0, then
      return 0
   define coins array of size value + 1, fill with ∞
   coins[0] := 0

   for i := 1 to value, do
      for j := 0 to n, do
         if coinList[j] <= i, then
            tempCoins := coins[i-coinList[j]]
         if tempCoins ≠ ∞ and (tempCoins + 1) < coins[i], then
            coins[i] := tempCoins + 1
      done
   done

   return coins[value]
End

Example

#include<iostream>
using namespace std;

int minCoins(int coinList[], int n, int value) {
   int coins[value+1];       //store minimum coins for value i

   if(value == 0)
      return 0;              //for value 0, it needs 0 coin

   coins[0] = 0;

   for (int i=1; i<=value; i++)
      coins[i] = INT_MAX;            //initially all values are infinity except 0 value

   for (int i=1; i<=value; i++) {      //for all values 1 to value, find minimum values
      for (int j=0; j<n; j++)
         if (coinList[j] <= i) {
            int tempCoins = coins[i-coinList[j]];
         if (tempCoins != INT_MAX && tempCoins + 1 < coins[i])
            coins[i] = tempCoins + 1;
      }
   }
   return coins[value];       //number of coins for value
}

int main() {
   int coins[] = {1, 2, 5, 10};
   int n = 4, value;
   cout << "Enter Value: "; cin >> value;
   cout << "Minimum "<<minCoins(coins, n, value)<<" coins required.";
   return 0;
}

Output

Enter Value: 48
Minimum 7 coins required.

Updated on: 17-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements