题目来源
题目描述
小明是一个销售员,客人在他的地方买了东西,付给了小明一定面值的钱之后,小明需要把多余的钱退给客人。客人付给了小明n,小明的东西的售价为m,小明能退回给客人的面额只能为[100,50,20,10,5,2,1]的组合。现在小明想要使纸币数量之和最小,请返回这个最小值。
1 <= m <= n <= 10000000001≤m≤n≤1000000000
样例
Give n=100, m=29, return 3.
100-29=71
Ming retrieved one 50, one 20 and one 1.
So the answer is 3.
Give n=50, m=5, return 3.
50-5=45
Ming retrieved two 20 and one 5.
So the answer is 3
思路
贪心
- 目标要使得找出去的钱最小,那么从最大的钱开始找,能找大面额的尽量找大面额的,否则尝试小面额的。
#include <set>
#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
private:
std::vector<int> comb {100, 50, 20, 10, 5, 2, 1};
public:
int coinProblem(int n, int m) {
int mon = n - m; // 还需要找多少钱
int res = 0; // 一共找出去的钱的张数
for (int i : comb){
res += mon / i; // 当前面额最大可以找多少钱
mon = mon % i; // 还剩下多少钱需要找
}
return res;
}
};
int main(){
Solution a;
std::cout << a.coinProblem(100, 29);
}