Fix the transfer runner for account balances
Your task
An AI's Java transfer method read both balances, checked for enough funds, then wrote both back, all inside @Transactional. Under load, two transfers read the same balance, both passed the check, and one debit was lost. The fix makes the check and the debit one step against the current balance. You model it by applying a list of transfers in order.
An assistant wrote apply_transfers(balances, transfers). It is in the editor. It has a bug. Find it and fix it.
Input and output:
balances: each account's balance, in cents. The account's number is its index.transfers: the transfers to apply, in order, each writtenfrom,to,amount.- Return the final balances.
Rules the tests check:
- Skip a transfer unless all of these hold:
- it splits on
,into exactly 3 parts, each an optional-followed by one or more digits from 0 to 9 fromandtoare valid indexes intobalances, and they differamountis above 0- the
fromaccount's current balance, after every earlier transfer, is at leastamount
- it splits on
- Otherwise move
amountfrom thefromaccount to thetoaccount.
Examples
apply_transfers(balances: list[int], transfers: list[str]) -> list[int]Example 1
Input
apply_transfers([1000, 500], ["0,1,300"])Output
[700, 800]Example 2
Input
apply_transfers([100, 100], ["0,1,150"])Output
[100, 100]Example 3
Input
apply_transfers([100, 0], ["0,1,100", "0,1,1"])Output
[0, 100]