![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find minimum number of currency notes and values that sum to given amount in C++
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
#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
Advertisements