A credit heap keyed by expiry drops each expired credit when it reaches the top
The practice problem's credits sit in a heap keyed by expiry. Tuples can't be changed, so entries that change are lists: [expires, count, credit_id, left].
When a spend looks at the top and finds a credit that has expired, it drops it and looks again, at O(log n) per drop. A credit that's partly used stays on top with less left. That's safe, because the amount left isn't part of the key.
Here a spend of 60 at time 12 meets three credits. Each row is one look at the top:
| Top | Expires, left | What happens | Still to pay |
|---|---|---|---|
| trial | 10, 20 | expired, since 10 <= 12: pop it | 60 |
| promo | 30, 50 | pays 50, stays on top | 10 |
| promo | 30, 0 | nothing left: pop it | 10 |
| base | never, 100 | pays 10, stays on top with 90 | 0 |
A credit used up exactly can stay in the heap with 0 left, until the next spend reaches it. That's lazy deletion again. Anything that adds up the balance has to skip it, or simply add its 0. Popping it the moment it hits 0 works just as well.
In the editor, write spend(heap, amount, now), the spend from the table. Look at the top credit again and again: drop it if it has expired or is empty, and otherwise take what it can pay. Return the part nothing could pay.