【数据结构】算法 Lemonade Change 柠檬水零钱
2021/4/10 12:27:58
本文主要是介绍【数据结构】算法 Lemonade Change 柠檬水零钱,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
目录- Lemonade Change 任务调度器
- 思路
- tag
Lemonade Change 任务调度器
At a lemonade stand, each lemonade costs $5
.
Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills
).
Each customer will only buy one lemonade and pay with either a $5
, $10
, or $20
bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5.
Note that you don't have any change in hand at first.
Return true
if and only if you can provide every customer with correct change.
一杯柠檬水5$,开始时没有任何钱,每个客户一次买一杯,但是可能会支付5,10,20的现金,如果现有的钱能够完成所有客户的找零,最后返回true,否则false
Input: [5,5,5,10,20] Output: true Explanation: From the first 3 customers, we collect three $5 bills in order. From the fourth customer, we collect a $10 bill and give back a $5. From the fifth customer, we give a $10 bill and a $5 bill. Since all customers got correct change, we output true.
思路
遇到需要找零的情况,先使用10+5,不够再使用5*3,原则是保留更多的5以便后面找零。
class Solution { public boolean lemonadeChange(int[] bills) { int cnt5= 0,cnt10 =0; for (int bill : bills) { switch (bill){ case 5: cnt5+=1; break; case 10: if (cnt5==0){ return false; } cnt5-=1; cnt10+=1; break; case 20: if(cnt5>=1&&cnt10>=1){ cnt5-=1; cnt10-=1; } else if (cnt5>=3){ cnt5 = cnt5-3; } else { return false; } break; } } return true; } }
tag
贪心
这篇关于【数据结构】算法 Lemonade Change 柠檬水零钱的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-25【机器学习(二)】分类和回归任务-决策树(Decision Tree,DT)算法-Sentosa_DSML社区版
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享