Greedy The best choice now
500. Lemonade Change
You run a lemonade stand, and each cup costs 5. Customers stand in a line and you serve them in order.
Customer i buys one cup and pays with a single bill, bills[i], which is a 5, a 10 or a 20. Each
customer must get change back, so that they pay exactly 5.
The stand starts with no money at all. You can give change only from the bills that earlier customers paid with, and each customer gets their change before the next one is served.
Return true if you can give every customer the right change, and false otherwise.
Example 1
Input: bills = [5, 5, 5, 10, 20, 10, 5]
trueExplanation: The first three customers pay exactly 5. The fourth gets a 5 back, and the fifth gets a 10 and a 5. The sixth gets the last 5, and the seventh pays exactly.
Example 2
Input: bills = [5, 5, 10, 10, 20]
falseExplanation: When the last customer pays 20, we hold two 10s and no 5. That is 20 in all, but no mix of those bills makes 15.
Example 3
Input: bills = [10, 5]
falseExplanation: The first customer needs a 5 back, and we have no money yet. The 5 from the second customer comes too late.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ bills.length ≤ 105bills[i]is 5, 10 or 20.
Clarifying questions
What you would ask an interviewer before writing any code.