Greedy Algorithms8 sections · 316 units
Open in Course

Lemonade - Algorithm

Track your bills

Keep count of 5and5 and 10 bills you have:

1.1. Customer pays $5: take it (fives += 1)

2.2. Customer pays 10:giveone10: give one 5 back if possible (fives -= 1, tens += 1)

3.3. Customer pays 20:prefergivingone20: prefer giving one 10 + one 5;elsegivethree5; else give three 5s If you ever cannot give correct change, return false. No need to track 20billssinceyounevergivethemaschange.Time:20 bills since you never give them as change. Time: O(n \log n).Space:. Space: O(1).Thetimecomplexityis. The time complexity is O(n),not, not O(n log n)$, because you do not need to sort. You process bills in the order customers arrive.