Unmatched Refunds — Puzzles: original problems
Replay payments and refunds in order, where each refund cancels an earlier open payment of equal size; count what stays unresolved.
Puzzles: original problems · Easy
The problem
Each entry of amounts is a payment (positive) or a refund (negative). A refund of -x cancels one earlier payment of x that is still uncancelled. A refund with no such payment cancels nothing, and a payment never cancels an earlier refund. Return how many entries end up neither cancelled nor cancelling anything.
The story
A shop's till logs 1 to 16 entries in order, each a payment (positive) or a refund (negative) of 1 to 6 coins. A refund of x coins undoes one earlier payment of x coins that nobody has undone yet; if there is none, the refund just sits there. A payment never undoes an earlier refund. At closing, the manager wants to know how many entries are still unresolved.
What to return
- Return the number of entries that are not cancelled and did not cancel anything.
- A refund cancels at most one payment, and a payment is cancelled at most once.
Constraints
- 1 <= amounts.length <= 16
- each amount is a non-zero integer from -6 to 6
Example
- Input
amounts = [4, 2, -4, 3]- Output
2