Find minimum number of currency notes and values that sum to given amount in C++

C++Server Side ProgrammingProgramming

Suppose we have such amount, and we have to find the minimum number of notes of different denominations, that sum up to the given amount. Start from highest denomination notes, try to find as many notes possible for given amount. Here the assumption is that we have infinite amount of {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1}. So if the amount is say 800, then notes will be 500, 200, 100.

Here we will use the greedy approach to solve this problem.

Example

 Live Demo

#include<iostream>
using namespace std;
void countNotes(int amount) {
   int notes[10] = { 2000, 500, 200, 100, 50, 20, 10, 5, 2, 1 };
   int noteFreq[10] = { 0 };
   for (int i = 0; i < 10; i++) {
      if (amount >= notes[i]) {
         noteFreq[i] = amount / notes[i];
         amount = amount - noteFreq[i] * notes[i];
      }
   }
   cout << "Note count:" << endl;
   for (int i = 0; i < 9; i++) {
      if (noteFreq[i] != 0) {
         cout << notes[i] << " : " << noteFreq[i] << endl;
      }
   }
}
int main() {
   int amount = 1072;
   cout << "Total amount is: " << amount << endl;
   countNotes(amount);
}

Output

Total amount is: 1072
Note count:
500 : 2
50 : 1
20 : 1
2 : 1
raja
Published on 17-Dec-2019 11:09:55
Advertisements