分析
初始化就是各个面额张数都是0 deposit就是对应加入面额
withdraw很关键 从大面额开始选 如果没有大面额了就continue了 然后看看大面额最多能选most,若超过张树,则设置为张树 然后amount 减去这么多张大面额的 同时used来记录当前用的 如果amount刚好为0了 就依次减掉原有张数(减掉used) 然后返回used 若不存在全部用完直接返回-1
ac code
class ATM:
def __init__(self):
self.c = [0, 0, 0, 0, 0]
def deposit(self, banknotesCount: List[int]) -> None:
for i in range(5):
self.c[i] += banknotesCount[i]
def withdraw(self, amount: int) -> List[int]:
cur = self.c[:]
used = [0] * 5
money = [20, 50, 100, 200, 500]
for i in range(4, -1, -1):
if cur[i] == 0:
continue
most = amount // money[i]
if most >= cur[i]:
most = cur[i]
amount -= most * money[i]
used[i] += most
if amount == 0:
for i in range(5):
self.c[i] -= used[i]
return used
return [-1]
总结
这道题不应该花这么多时间 贪心的知识不够牢固!
|