Ferry Fare Change

EasygreedyAlso known as Lemonade Change

You run the ticket window for a river ferry. A crossing costs $5, and each passenger pays with one $5, $10 or $20 bill. Your cash box starts empty, so the only change you can give is bills earlier passengers paid with. You know today's queue in advance and want to find out whether everyone can be served.

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

After two exact payments the box holds two $5. The $10 passenger gets a $5 back, leaving one $5 and one $10. The $20 passenger needs $15, so you give back the $10 and the $5.

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

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

Constraints

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

Each $20 passenger can get change up to two ways. Trying both options for each of them means up to 2k sequences for k such passengers, which is about a trillion for 40. Most of that work is wasted, because one choice is never worse than the other.

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