C++ 0860.cpp
class Solution {
public:
bool lemonadeChange(vector<int>& bills) {
// order is important !
int c[21];
c[5] = c[10] = c[20] = 0;
for (auto x : bills)
{
c[x]++;
switch (x)
{
case 5: break;
case 10: if (c[5] == 0) return false; c[5]--; break;
case 20: if (c[5] == 0) return false;
if (c[10] == 0)
{
if (c[5] < 3)
return false;
c[5] -= 3;
}
else
{
c[5]--;
c[10]--;
}
break;
}
}
return true;
}
};
Difficulty
and has an acceptance rate of about 59% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Greedy
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented implementation solves the classic “lemonade change” problem. It receives a sequence of customer payments (bills) and determines whether a vendor can provide correct change for each transaction using only the cash on hand. The algorithm processes the payments in order, maintains a count of each denomination, and applies a deterministic change-making strategy.
Core Logic
The function begins by allocating a fixed-size integer array c[21]. Only the entries for the denominations 5, 10, and 20 are used, and they are initialized to zero. This array acts as a compact counter for the cash drawer.
int c[21];
c[5] = c[10] = c[20] = 0;
A range-based for loop iterates over every bill in the input vector. For each bill the corresponding counter is incremented, then a switch statement decides how to dispense change.
for (auto x : bills)
{
c[x]++;
switch (x)
{
// cases handled below
}
}
Handling a $5 Payment
When the customer pays with a $5 bill, no change is required. The algorithm simply records the receipt of the bill and proceeds.
case 5: break;
Handling a $10 Payment
A $10 payment requires $5 in change. The code checks whether at least one $5 bill is available. If not, the function returns false immediately, indicating that the transaction cannot be completed. Otherwise, one $5 bill is removed from the drawer.
case 10:
if (c[5] == 0) return false;
c[5]--;
break;
Handling a $20 Payment
A $20 payment requires $15 in change. The implementation prefers to give one $10 and one $5 when possible, because this conserves $5 bills for future transactions. The logic proceeds in three stages:
- Verify that at least one $5 bill exists; otherwise the transaction fails.
- If no $10 bill is present, the algorithm must use three $5 bills. It checks that at least three $5 bills are available; if not, it returns
false. When sufficient, it deducts three $5 bills. - If a $10 bill is available, it gives one $10 and one $5, decrementing both counters.
case 20:
if (c[5] == 0) return false;
if (c[10] == 0)
{
if (c[5] < 3) return false;
c[5] -= 3;
}
else
{
c[5]--;
c[10]--;
}
break;
After processing all bills, the function reaches the final statement and returns true, confirming that every customer received correct change.
return true;
Edge Cases Addressed
The algorithm explicitly guards against several boundary conditions:
- A $10 bill arriving when the drawer contains no $5 bills triggers an early exit, preventing an impossible change scenario.
- A $20 bill is rejected if the drawer lacks any $5 bill, because $5 is a mandatory component of the $15 change.
- When a $20 bill arrives and the drawer has no $10 bills, the code ensures that at least three $5 bills are present before proceeding, thereby avoiding a shortfall.
- The case where the drawer has exactly one $10 and one $5 is handled correctly, as the algorithm will use that combination rather than attempting to use three $5 bills unnecessarily.
These checks guarantee that the function never attempts to decrement a counter below zero, preserving logical consistency throughout the iteration.
Performance Optimizations
The solution employs several low-overhead techniques that contribute to its efficiency:
- Fixed-size array for counters: Using a static array of size 21 eliminates the need for dynamic containers such as
std::maporstd::unordered_map. Indexing by the bill value provides O(1) access without hashing overhead. - In-place counter updates: Incrementing the appropriate counter before the
switchensures that the current bill is already accounted for when change is calculated, avoiding an extra lookup. - Early termination: The function returns
falseimmediately upon detecting an unsatisfiable transaction. This prevents unnecessary processing of the remaining bills, which can be significant for long input sequences. - Preferential change strategy: By giving a $10 and a $5 when possible, the algorithm reduces the consumption of $5 bills, which are the most versatile for future change. This heuristic minimizes the likelihood of later failures without additional computation.
- Range-based loop: The
for (auto x : bills)construct iterates directly over the elements, avoiding index calculations and potential bounds checks associated with traditional indexed loops.
Collectively, these choices keep the runtime linear in the number of bills and maintain a minimal memory footprint, making the solution well-suited for environments with tight performance constraints.
ELI5 - Simplified Explanation
Imagine running a little lemonade stand where every cup costs five dollars. Friends come up to your counter one by one to buy a drink, but they pay with different bills. Some hand you a five-dollar bill, which is perfect and easy to take. Other friends might hand you a ten-dollar bill, which means you have to give them a five-dollar bill back as change. Some friends even hand you a twenty-dollar bill, which is a bit trickier because you need to give them back fifteen dollars total.
To keep everything working, you keep three special piggy banks to store the money you collect. One bank is for the five-dollar bills, one is for the tens, and one is for the twenties. Every time someone buys a lemonade, you first put their money into the right piggy bank. Then, you look at your collection to see if you have the right change to give back to them. If someone gives you a ten, you check if you have at least one five-dollar bill in your pile. If someone gives you a twenty, you look to see if you can give back fifteen dollars. You try to give one ten and one five, but if you do not have a ten, you check if you have three five-dollar bills instead. If at any point you realize you do not have enough money in your piggy banks to give your friend their change, that means the lemonade stand has run out of the right coins and you have to close up shop. This code acts exactly like a helper who watches these piggy banks to make sure there is always enough change to keep the customers happy as they arrive.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | JS | Rust | Python | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| gouthampradhan | Java | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| Shamik07 | Dart | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality