Algorithm/src/main/java/greedy/LemonadeChange.java
2025-04-09 12:50:45 +08:00

69 lines
2.6 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package greedy;
import java.util.ArrayList;
import java.util.List;
/**
* 题目: 860. 柠檬水找零 (lemonadeChange)
* 描述:在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
* 每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
* 注意,一开始你手头没有任何零钱。
* 给你一个整数数组 bills ,其中 bills[i] 是第 i 位顾客付的账。如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
*
* 示例 1
输入bills = [5,5,5,10,20]
输出true
解释:
前 3 位顾客那里,我们按顺序收取 3 张 5 美元的钞票。
第 4 位顾客那里,我们收取一张 10 美元的钞票,并返还 5 美元。
第 5 位顾客那里,我们找还一张 10 美元的钞票和一张 5 美元的钞票。
由于所有客户都得到了正确的找零,所以我们输出 true。
* 链接https://leetcode.cn/problems/lemonade-change/
*/
public class LemonadeChange {
public boolean lemonadeChange(int[] bills) {
int five = 0; // 记录 5 美元的数量
int ten = 0; // 记录 10 美元的数量
// 遍历每一笔账单
for (int bill : bills) {
switch (bill) {
case 5:
// 收到 5 美元,不需找零
five++;
break;
case 10:
// 收到 10 美元,需要找回 5 美元
if (five > 0) {
five--; // 找回一张 5 美元
ten++; // 保存这张 10 美元
} else {
return false;
}
break;
case 20:
// 收到 20 美元,需要找回 15 美元
// 优先使用一张 10 美元和一张 5 美元找零
if (ten > 0 && five > 0) {
ten--;
five--;
}
// 如果没有 10 美元,则用三张 5 美元找零
else if (five >= 3) {
five -= 3;
} else {
return false;
}
break;
default:
return false;
}
}
return true;
}
}