herrDeng網內搜尋

自訂搜尋

Ads

2024年8月15日 星期四

python C++ Greedy速解找零問題Leetcode 860 Lemonade Change


python C++ Greedy速解找零問題Leetcode 860  Lemonade Change
b=20時貪婪演算法保持檢查順序,先找十塊,不要改變檢查順序,否則不起作用
[python解請進]
-----
When b=20, the greedy algorithm maintains the checking order. Give back $10 first, and do not change the checking order, otherwise it will not work.

  1. class Solution:
  2. def lemonadeChange(self, bills: List[int]) -> bool:
  3. cnt5, cnt10=0, 0
  4. for b in bills:
  5. if b==5: cnt5+=1
  6. elif b==10:
  7. if cnt5>0:
  8. cnt5-=1
  9. cnt10+=1
  10. else:
  11. return False
  12. else:
  13. if cnt10>0 and cnt5>0:
  14. cnt10-=1
  15. cnt5-=1
  16. elif cnt5>2: cnt5-=3
  17. else: return False
  18. return True

沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章