GPU Credit Ledger
OpenAIPhone screenMedium
Build an in-memory ledger of expiring GPU credits for many users. Each grant adds a separate lot of credits that stops being usable at its expiry time; a charge is always taken from the lots that expire soonest. Users never affect each other.
A lot is valid at time t exactly when t < expiry. At t == expiry it is already expired: it does not count toward the balance and cannot be spent.
Every method that takes a time at is called with times that never decrease from one such call to the next, across all users. grant takes no time and can be called at any point.
Each test drives one CreditLedger() instance through a sequence of calls and checks every return value.
Part 1: Grants, charges and balance
Implement:
grant(user, amount, expiry)adds a lot ofamountcredits that expires atexpiry. A grant withamount <= 0is ignored. Returns nothing.charge(user, amount, at)spendsamountcredits from the lots valid atat, always taking from the lot with the earliest expiry first, using several lots (and part of the last) when needed. If the valid lots hold less thanamountin total, it returnsFalseand changes nothing; otherwise it returnsTrue. A charge of0always returnsTrue.balance(user, at)returns the total credits in lots valid atat.
A user with no grants has balance 0.
- Example 1
- init
[]- operations
[["grant",["alice",10,5]],["grant",["alice",30,20]],["charge",["alice",10,5]],["balance",["alice",5]],["charge",["alice",21,6]],["balance",["alice",6]]]- Output
[null,null,true,20,false,20]
Why: The lot of 10 expires at 5, so at time 5 it is already gone: the charge of 10 at time 5 is taken from the 30-lot, leaving 20. The charge of 21 at time 6 needs more than the 20 left, so it fails and changes nothing.
Constraints
- 1 <= len(
operations) <= 2 * 10^4 - 0 <=
amount<= 10^9 - 0 <=
expiry<= 10^9 - 0 <=
at<= 10^9 atnever decreases acrosschargeandbalancecalls