Ferry Fare Change

EasygreedyAlso known as Lemonade Change

You run the ticket window for a small river ferry. A crossing costs $5. Passengers pay with a single $5, $10 or $20 bill, and you must hand back exact change on the spot.

Your cash box starts empty in the morning. The only money you can give as change is the bills earlier passengers paid with. You know the order of today's passengers and the bill each will hand you. Can you serve all of them?

Your task

Write canGiveChange(bills). bills[i] is the bill the i-th passenger pays with, in queue order. Each passenger buys exactly one $5 ticket. Return true if you can give every passenger correct change, and false as soon as one passenger cannot get it.

Bills you receive go into the cash box and can be used as change for later passengers. An empty queue returns true.

canGiveChange(bills: int[]) → bool

Examples

Example 1
Input
bills = [5, 5, 10, 20]
Output
true
Why

The first two passengers pay exactly: the box holds two $5. The third pays $10 and gets one $5 back: the box holds one $5 and one $10. The fourth pays $20 and needs $15: give the $10 and the $5. Everyone is served.

Example 2
Input
bills = [5, 10, 10]
Output
false
Why

After the first two passengers, the box holds one $10 and no $5. The third passenger needs $5 back, and a $10 bill cannot be split. Fail.

Constraints

  • 0 ≤ bills.length ≤ 100,000
  • bills[i] is 5, 10 or 20
Start with brute force

For every $20 passenger there are up to two ways to make change. You could try both ways for each of them and see if any sequence of choices serves the whole queue. With k passengers paying $20 that is up to 2k sequences, so 40 such passengers already means about a trillion tries.

The branching is wasted work: one of the two choices is never worse than the other, so you never need to try both.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code