Problem 860

Abstract / Summary

A cashier gives change to customers buying lemonade and must always give the correct coins when possible.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
31 lines | 906 bytes | submitted August 7, 2023 | GitHub   3% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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:

  1. Verify that at least one $5 bill exists; otherwise the transaction fails.
  2. 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.
  3. 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::map or std::unordered_map. Indexing by the bill value provides O(1) access without hashing overhead.
  • In-place counter updates: Incrementing the appropriate counter before the switch ensures that the current bill is already accounted for when change is calculated, avoiding an extra lookup.
  • Early termination: The function returns false immediately 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.11 | σ = 0.99

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
36 links | 21 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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