Payments app~25 min2s · 256 MBtarget O(n x m) time, O(n) spaceshortest-paths
A payments app moves money between accounts, numbered from 0, through one-way transfers. Each transfer has a fee in units. Some transfers pay a rebate, which counts as a negative fee.
A payment may pass through several accounts, and the total fee is the sum of the fees of its transfers. Finance promises that no loop of transfers has a negative total, so no one can earn money by going round. You want the lowest total fee from a source account to a target account.
Write cheapest_with_rebates(n, transfers, source, target).
n accounts, numbered from 0 to n - 1.transfers[i] is [from, to, fee]: a one-way transfer. The fee may be negative. Several transfers may join the same pair.source to target. When source equals target, the answer is 0.Input: n = 5, transfers = [[3,4,-2],[2,3,2],[1,2,-3],[0,1,4],[0,2,5],[1,3,6]], source = 0, target = 4
Output: 1The chain 0, 1, 2, 3, 4 costs 4 - 3 + 2 - 2 = 1. The direct transfer from 0 to 2 costs 5, so the longer chain wins.
The solution runs rounds. In each round it tries every transfer in the list order, and lowers the fee of an account when a transfer gives a lower one. The transfers are listed from the end of the chain to the start, so each round advances one step.
| After round | Account 0 | Account 1 | Account 2 | Account 3 | Account 4 |
|---|---|---|---|---|---|
| 0 | 0 | none | none | none | none |
| 1 | 0 | 4 | 5 | 10 | none |
| 2 | 0 | 4 | 1 | 7 | 8 |
| 3 | 0 | 4 | 1 | 3 | 5 |
| 4 | 0 | 4 | 1 | 3 | 1 |
After round 4 the fee of account 4 is 1. A fifth round would change nothing.
Input: n = 3, transfers = [[0,1,10],[1,2,-4]], source = 0, target = 2
Output: 6The first transfer costs 10 and the second pays a rebate of 4, so the chain costs 6.
Input: n = 3, transfers = [[1,2,-5]], source = 0, target = 2
Output: 1000000000000Account 0 has no transfer, so account 2 cannot be reached.
1 ≤ n ≤ 20,000, 0 ≤ source < n and 0 ≤ target < n0 ≤ transfers.length ≤ 100,000, and each transfer is [from, to, fee] with 0 ≤ from, to < n and -1,000 ≤ fee ≤ 1,000Trying every chain that does not repeat an account can mean w^L chains for L layers of w accounts. For 40 layers of 50 accounts that is 50^40. Repeating rounds over all transfers costs at most n × m = 2 × 10^9 steps in the worst case, and far less when the rounds stop early.