Start learning free

LESSON 509 OF 642 · GREEDY

Lemonade Change in Rust

Practice O(n)

You get an array bills. Each number is the bill one customer pays with.

One lemonade costs 5, and each customer buys one. Return true if every customer can get the right change. Otherwise, return false.

Customers are served in the order of bills. Each bill is a 5, a 10 or a 20.

You start with no bills. Your change can only come from bills that customers paid before.

 

Example 1:

Input: bills = [5,10,5,20]
Output: true
Explanation: The first customer pays exactly 5.
The second pays 10 and gets that 5 back.
The third pays 5.
The fourth pays 20 and gets the 10 and the 5 back.

Example 2:

Input: bills = [5,5,20]
Output: false
Explanation: The third customer needs 15 back.
You hold only two 5s, which make 10.

Example 3:

Input: bills = [5,5,5,5,10,20,10]
Output: true
Explanation: Before the 20, you hold three 5s and one 10.
For the 20, give back the 10 and a 5.
That leaves two 5s, so the last customer gets a 5 back.
Three 5s for the 20 would leave no 5 for the last customer.

 

Constraints:

  • 1 to 100,000 customers.
  • Each bill is 5, 10 or 20.

Note:

Your solution should run in O(n) time and use O(1) extra space.

STEP 1 OF 12
    Ctrl + Enter to check

    Lemonade Change in Rust

    Keep going with Rust500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free