Suppose you are a cashier at a lemonade stand, and each lemonade costs $5. Customers queue up to buy from you, and they may pay with a $5, $10, or $20 bill. You need to provide them with the correct change using the bills you have so far. Initially, you start with no change.
Write a function lemonadeChange
that takes in a list of integers representing the bills customers use to pay for their lemonade and returns True
if you can provide every customer with the correct change, or False
otherwise.
Input: [5, 5, 5, 10, 20]
Output: True
Input: [5, 5, 10, 10, 20]
Output: False
False
.False
.True
.def lemonadeChange(bills):
five_dollar_count = 0
ten_dollar_count = 0
for bill in bills:
if bill == 5:
five_dollar_count += 1
elif bill == 10:
if five_dollar_count > 0:
five_dollar_count -= 1
ten_dollar_count += 1
else:
return False
elif bill == 20:
if ten_dollar_count > 0 and five_dollar_count > 0:
ten_dollar_count -= 1
five_dollar_count -= 1
elif five_dollar_count >= 3:
five_dollar_count -= 3
else:
return False
return True
# Example usage
print(lemonadeChange([5, 5, 5, 10, 20])) # Output: True
print(lemonadeChange([5, 5, 10, 10, 20])) # Output: False
This approach ensures that every transaction is considered in sequence and the appropriate change is given, if possible, thus ensuring all customers are satisfied.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?