【代码随想录day 29】 力扣 860.柠檬水找零
视频讲解:https://www.bilibili.com/video/BV12x4y1j7DD/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0860.%E6%9F%A0%E6%AA%AC%E6%B0%B4%E6%89%BE%E9%9B%B6.html#%E6%80%9D%E8%B7%AF
力扣题目:https://leetcode.cn/problems/lemonade-change/
这道题乍一看很难,但其实没有几个判断情况
- 如果第一个上来就不能找零,直接false
- 收到5元,不用找零,收到10元,找5元
- 收到20就需要找一个5一个10或者三个5
- 一旦出现小于0的情况下,直接false,否则则为true
class Solution {
public:bool lemonadeChange(vector<int>& bills) {int cash_5 = 0;int cash_10 = 0;int cash_20 = 0;//剪枝if(bills[0] != 5){return false;}for(int i = 0; i < bills.size(); ++i){if(bills[i] == 5){cash_5++;}if(bills[i] == 10){cash_10++;cash_5--;}if(bills[i] == 20){if(cash_10 == 0){cash_20++;cash_5 -= 3;}else{cash_20++;cash_10--;cash_5--;}}if(cash_5 < 0 ||cash_10 < 0 || cash_20 < 0){return false;}}return true;}
};