Greedy Algorithm to find Minimum number of Coins
Given an amount of n Rupees and an infinite supply of each of the denominations {1, 2, 5, 10} valued coins/notes, The task is to find the minimum number of coins needed to make the given amount.
Examples:
Input: n= 39
Output: 6
Explanation: We need a 50 Rs note and a 20 Rs note.Input: n = 121
Output: 13
Explanation: We need a 100 Rs note, a 20 Rs note, and a 1 Rs coin.
Approach - O(n) Time and O(n) Space
The 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.
#include <bits/stdc++.h>
using namespace std;
int findMin(int n, vector<int> denomination)
{
int count=0;
// Traverse through all denomination
for (int i = denomination.size() - 1; i >= 0; i--) {
// Find denominations
while (n >= denomination[i]) {
n -= denomination[i];
count++;
}
}
return count;
}
int main()
{
vector<int> denomination = { 1, 2, 5, 10 };
int n = 39;
cout<<findMin(n, denomination);
return 0;
}
public class GfG {
// Function to find the minimum number of coins
public static int findMin(int n, int[] denomination) {
// Traverse through all denominations in reverse order
int count =0;
for (int i = denomination.length - 1; i >= 0; i--) {
// Find denominations
while (n >= denomination[i]) {
n -= denomination[i];
count ++;
}
}
return count;
}
public static void main(String[] args) {
int[] denomination = {1, 2, 5, 10};
int n = 39;
System.out.print(findMin(n, denomination));
}
}
def findMin(n, denomination):
count =0
# Traverse through all denomination
for i in range(len(denomination) - 1, -1, -1):
# Find denominations
while n >= denomination[i]:
n -= denomination[i]
count +=1
return count
if __name__ == '__main__':
denomination = [1, 2, 5, 10]
n = 39
print(findMin(n, denomination))
using System;
using System.Collections.Generic;
class GfG {
static int findMin(int n, List<int> denomination) {
// Traverse through all denomination
int count = 0;
for (int i = denomination.Count - 1; i >= 0; i--) {
// Find denominations
while (n >= denomination[i]) {
n -= denomination[i];
count++;
}
}
return count;
}
static void Main() {
List<int> denomination = new List<int> { 1, 2, 5, 10 };
int n = 39;
Console.Write(findMin(n, denomination));
}
}
function findMin(n, denomination) {
// Traverse through all denomination
var count =0;
for (let i = denomination.length - 1; i >= 0; i--) {
// Find denominations
while (n >= denomination[i]) {
n -= denomination[i];
count += 1
}
}
return count;
}
const denomination = [1, 2, 5, 10];
const n = 39;
console.log(findMin(n, denomination));
Output
6
Note: The above approach may not work for all denominations.
For example, it doesn't work for denominations {9, 6, 5, 1} and n = 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 :