在柠檬水摊上,每一杯柠檬水的售价为 5
美元。顾客排队购买你的产品,(按账单 bills
支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5
美元、10
美元或 20
美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5
美元。
注意,一开始你手头没有任何零钱。
给你一个整数数组 bills
,其中 bills[i]
是第 i
位顾客付的账。如果你能给每位顾客正确找零,返回 true
,否则返回 false
。

思路:
找当前列表中是否满足当下金额。
python3实现:
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
# 看看列表中的数据是否满足该次的需求就行了
current_list = []
for idx in range(len(bills)):
print("此时:", current_list," 客户钱:",bills[idx])
if bills[idx] == 5:
current_list.append(5)
if bills[idx] == 10:
if 5 in current_list:
current_list.remove(5)
current_list.append(10)
else:
print("没有零钱5")
return False
if bills[idx] == 20:
if 5 in current_list and 10 in current_list:
current_list.remove(5)
current_list.remove(10)
current_list.append(20)
elif 5 in current_list and 10 not in current_list:
if current_list.count(5) >= 3:
current_list.remove(5)
current_list.remove(5)
current_list.remove(5)
current_list.append(20)
else:
return False
else:
print("没有零钱5或10")
return False
return True

超时啦!换个思路。
直接统计个数:
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
# 直接找到对应的公式
# 1张20至少要有1个10和1个5,或者3张5
# 1张10至少要1个5
# 然后统计20和10的个数就行了
count_20 = bills.count(20)
count_10 = bills.count(10)
need_five_count_a1 = count_20
need_ten_count_a1 = count_20
need_five_count_a2 = 3 * count_20
need_ten_count_a2 = 0
need_five_count_b = count_10
# 情况一
sis1_five_count = need_five_count_a1 + need_five_count_b
sis1_ten_count = need_ten_count_a1
# 情况二
sis2_five_count = need_five_count_a2 + need_five_count_b
sis2_ten_count = need_ten_count_a2
true_sistuation_five_count = bills.count(5)
true_sistuation_ten_count = bills.count(10)
if true_sistuation_five_count >= sis1_five_count and true_sistuation_ten_count >= sis1_ten_count:
return True
if true_sistuation_five_count >= sis2_five_count and true_sistuation_ten_count >= sis2_ten_count:
return True
return False

因为这个有顺序限制!!!!!!!!!!!
再换个思路,这一次用当下有的去预测未来的false。
做不出来了先放着。