Problem 328892 · easy · Level 03 Linear Management & Searching

Ferry Ticket Change

greedy · simulation · counting

A ferry ticket costs 5. Customers queue up and each pays with a single bill of 5, 10 or 20, in the order given by bills. You start with no money and can only give change from bills you have already collected. Return True if you can give every customer exact change, otherwise False.

Examples

Input:  bills = [5, 10, 5, 5, 20]
Output: True
Explanation: The 10 gets the first 5 back; the 20 gets the 10 and one of the later 5s.
Input:  bills = [5, 10, 5, 10, 20]
Output: False
Explanation: Each 10 uses up a 5, so when the 20 arrives you hold two 10s and no 5s: 15 in change is impossible.

Constraints

  • An empty queue returns True.
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • Track how many of each bill you hold as customers arrive
  • Choose which bills to hand back when more than one combination works
  • Stop early as soon as a customer cannot be served
Starting Python…