Coin Change Problem---Introductory Example of Greedy Algorithm

I recently stumbled across a blog about greedy algorithms, which is really good. As an algorithm novice, I feel that this article is really good to get started, so I take one of the typical examples of greedy algorithms. Blog Portal: Learning Greedy Algorithms from Scratch


coin change problem

This problem is more common in our daily life. Suppose there are c0, c1, c2, c3, c4, c5, c6 banknotes of 1 yuan, 2 yuan, 5 yuan, 10 yuan, 20 yuan, 50 yuan, and 100 yuan respectively. Now to pay K yuan with this money, how many banknotes will it take? Using the idea of ​​greedy algorithm, it is obvious that each step can be done with a banknote with a large face value. We do this naturally in our daily life. In the program, the Values ​​have been arranged in order from small to large.

The code above:

#include<iostream>
#include<algorithm>
using namespace std;
const int N=7; 
int Count[N]={3,0,2,1,0,3,5};
int Value[N]={1,2,5,10,20,50,100};
  
int solve(int money) 
{
	int num=0;
	for(int i=N-1;i>=0;i--) 
	{
		int c=min(money/Value[i],Count[i]);
		money=money-c*Value[i];
		num+=c;
	}
	if(money>0) num=-1;
	return num;
}
 
int main() 
{
	int money;
	cin>>money;
	int res=solve(money);
	if(res!=-1) cout<<res<<endl;
	else cout<<"NO"<<endl;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325523774&siteId=291194637