Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-08-15 10:46:05
https://leetcode.com/problems/lemonade-change
860. Lemonade Change
檸檬水一杯 5 元 硬幣有 5 / 10 / 20 三種
按照訂單 高於價格的話要找零
如果能全部都順利找零 則為 true 反之則回傳 false
Example 1:
Input: bills = [5,5,5,10,20]
Output: true
Explanation: 前3個都獲得5元 第4個找5元 第5個找10+5元
Example 2:
Input: bills = [5,5,10,10,20]
Output: false
Explanation: 前2個都獲得5元 第3個與第4個都5元 第5個只有2個10元 沒有15元能找
思路:
照著做就好了
Python Code:
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
changes = {5: 0, 10: 0, 20: 0}
for bill in bills:
if bill == 5:
changes[5] += 1
continue
if not changes[5]:
return False
if bill == 10:
changes[10] += 1
changes[5] -= 1
else:
if not changes[10]:
if changes[5] < 3:
return False
changes[20] += 1
changes[5] -= 3
else:
changes[20] += 1
changes[10] -= 1
changes[5] -= 1
return True

Links booklink

Contact Us: admin [ a t ] ucptt.com