Lemonade Change Problem
Description
LeetCode Problem 860.
At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.
Note that you don't have any change in hand at first.
Given an integer array bills where bills[i] is the bill the i^th customer pays, return true if you can provide every customer with correct change, or false otherwise.
Example 1:
Input: bills = [5,5,5,10,20]
Output: true
Explanation:
From the first 3 customers, we collect three $5 bills in order.
From the fourth customer, we collect a $10 bill and give back a $5.
From the fifth customer, we give a $10 bill and a $5 bill.
Since all customers got correct change, we output true.
Example 2:
Input: bills = [5,5,10,10,20]
Output: false
Explanation:
From the first two customers in order, we collect two $5 bills.
For the next two customers in order, we collect a $10 bill and give back a $5 bill.
For the last customer, we can not give change of $15 back because we only have two $10 bills.
Since not every customer received correct change, the answer is false.
Example 3:
Input: bills = [5,5,10]
Output: true
Example 4:
Input: bills = [10,10]
Output: false
Constraints:
- 1 <= bills.length <= 10^5
- bills[i] is either 5, 10, or 20.
Solution
Approach: Greedy Change Counting
We only ever give back $5 and $10 bills ($20 bills are never useful as change), so it is enough to count how many of each we hold. Serve the customers in order:
- $5: keep it. No change needed.
- $10: give back one $5. If we have none, return
false. - $20: we owe $15. Pay it as $10 + $5 if we can, otherwise as $5 + $5 + $5. If neither works, return
false.
If every customer is served, return true.
The one choice is for $20, and the greedy rule is to spend the $10 first. A $5 bill can be used for any later change, while a $10 can only help with a later $20. So keeping $5 bills never hurts. For example, with bills = [5,5,5,5,10,20,10] we hold three $5 and one $10 before the $20. Paying with $10 + $5 leaves two $5, enough for the last $10. Paying with three $5 bills leaves none, and the last customer gets no change.
Complexity: O(n) time and O(1) space, where n is the length of bills.
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
fives = 0
tens = 0
for bill in bills:
if bill == 5:
fives += 1
elif bill == 10:
if fives == 0:
return False
fives -= 1
tens += 1
else: # a $20 bill needs $15 back
if tens > 0 and fives > 0:
tens -= 1 # give the $10 first: $5 bills are more useful later
fives -= 1
elif fives >= 3:
fives -= 3
else:
return False
return True
Now write it from memory
Close the write-up and solve it yourself against the tests.