NeetCode #763LC-860EasyGreedyNC 250
← Back to All Problems#763 · #860 · Lemonade Change(柠檬水找零)
📌 Problem Statement & Constraints
Each customer in a queue pays with a
5, 10 or 20 dollar bill for a 5 dollar lemonade. You start with no change. Return true if you can give every customer correct change, processing them in order. Constraints: 1 <= bills.length <= 10^4, bills[i] is 5, 10 or 20.💡 Core Algorithmic Approaches
- Only the counts of
5and10bills matter;20bills are never useful as change. - A
5needs no change; a10needs one5; a20needs either a10plus a5or three5bills. - For a
20, prefer the10 + 5combination because it preserves scarce5bills. - If any payment cannot be made, return false immediately.
💻 Benchmark Python3 Implementation
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five = ten = 0
for b in bills:
if b == 5:
five += 1
elif b == 10:
if five == 0:
return False
five -= 1
ten += 1
else: # 20
if ten > 0 and five > 0:
ten -= 1
five -= 1
elif five >= 3:
five -= 3
else:
return False
return True⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): a single pass.
💾 Space Complexity
O(1): two counters.
⚠️ Interview Pitfalls & Follow-ups
- Giving three
5bills for a20when a10 + 5is available: this wastes5bills that later customers may need. - Tracking
20bills: they can never be handed back as change, so counting them is pointless. - Processing customers out of order: the queue order is fixed and matters.
- Forgetting that a
10also requires a5in change: a10payment must be settled with exactly one5.