Amazon OA 面试真题解析:最少纸币和硬币找零

28次阅读
没有评论

Q1

Given a sum of money, compute the minimum number of bills and coins that equal that sum.

Assume you only have the following denominations:

  • Bills: 20, 10, 5, 1
  • Coins: 0.25, 0.10, 0.05, 0.01

For example, given 6.35 the solution would be one 5, one 1, one 0.25, one 0.10.

Q2

You will now be given a cash drawer that defines how much of each bill and coin you have to make change with. Now, given a sum of money and a cash drawer, compute the minimum number of bills and coins.

For example, given that you need to give change for 40.05 and you have a cash drawer of one 20, one 10, ten 5s, ten 0.1s, the solution would be one 20, one 10, two 5s, five 0.1s.

Notes before you get started:

  • Solve Q1 before moving on to Q2.
  • The solution will be evaluated on code maintainability. Think about how to organize your code to best solve Q1 and Q2.

这道 Amazon OA 题的核心是“找零最少张数 / 枚数”。Q1 是标准贪心:由于面额是 20、10、5、1 以及 0.25、0.10、0.05、0.01,先用最大的面额尽可能多地取,再继续向下处理即可得到最少数量。Q2 在此基础上增加了 cash drawer 的库存限制,需要先判断每种面额最多还能使用多少张 / 枚,再在贪心过程中把可用数量和目标金额同时考虑进去;金额涉及小数时,通常要统一转换成分单位(如 cents)来避免浮点误差。实现时可以把“面额列表 + 库存限制 + 选择逻辑”拆成可复用函数,方便同时解决 Q1 和 Q2,也符合题目对代码可维护性的要求。

正文完
 0