LeetCode—860. Lemonade Change [Lemonade Change]—Analysis and Code [Java]
1. Title
At the lemonade stand, each glass of lemonade sells for $5.
Customers line up to buy your products, (in the order of bills paid) one cup at a time.
Each customer only buys a glass of lemonade and then pays you $5, $10 or $20. You must give each customer the correct change, which means that the net transaction is that each customer pays you $5.
Note that you don't have any change at the beginning.
If you can give each customer the correct change, return true, otherwise return false.
Example 1:
输入:[5,5,5,10,20]
输出:true
解释:
前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。
由于所有客户都得到了正确的找零,所以我们输出 true。
Example 2:
输入:[5,5,10]
输出:true
Example 3:
输入:[10,10]
输出:false
Example 4:
输入:[5,5,10,10,20]
输出:false
解释:
前 2 位顾客那里,我们按顺序收取 2 张 5 美元的钞票。
对于接下来的 2 位顾客,我们收取一张 10 美元的钞票,然后返还 5 美元。
对于最后一位顾客,我们无法退回 15 美元,因为我们现在只有两张 10 美元的钞票。
由于不是每位顾客都得到了正确的找零,所以答案是 false。
prompt:
- 0 <= bills.length <= 10000
- bills[i] is either 5 or 10 or 20
Source: LeetCode
Link: https://leetcode-cn.com/problems/lemonade-change The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Two, analysis and code
1. Judge in turn
(1) Thinking
Store the number of 5 dollars and 10 dollars banknotes owned, and judge them in turn during the traversal process.
Since 5 US dollars can completely replace 10 US dollars, when 20 US dollars are charged, 10 US dollars are given priority to change.
(2) Code (iteration)
class Solution {
public boolean lemonadeChange(int[] bills) {
int [] cash = {
0, 0};
for (int bill : bills) {
switch(bill) {
case 5:
cash[0]++;
break;
case 10:
if (cash[0] == 0)
return false;
cash[0]--;
cash[1]++;
break;
case 20:
if (cash[1] > 0)
cash[1]--;
else
cash[0] -= 2;
cash[0]--;
if (cash[0] < 0)
return false;
break;
default:
return false;
}
}
return true;
}
}
(3) Results (iteration)
Execution time: 2 ms, beating 99.72% of users
in all Java submissions ; memory consumption: 39.5 MB, beating 68.87% of users in all Java submissions.
Three, other
Nothing.