Bank app~30 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-134greedy
A bank courier van drives a ring road past n branches, numbered from 0. At each branch the van collects the cash that the branch has ready, and then must carry enough cash to pay the next branch its requested amount.
The van's vault holds at most cap units, and cash collected beyond that is left behind. The van starts empty at its first branch.
You find the first branch from which the van can complete the whole ring.
Write first_start_with_cap(deposits, payouts, cap).
i, the van first collects deposits[i] units, and the vault then holds at most cap. It must then hold at least payouts[i] units to drive on to the next branch, and it uses them up.n - 1 it comes back to branch 0. The van starts empty, collects at its starting branch first, and visits each branch once.-1 if no branch works.Input: deposits = [4,2,6,1,3,5], payouts = [3,5,2,4,2,3], cap = 6
Output: 2The solution tries a start and drives round. When the van runs short at a branch, no start before that branch can work either, so the next try begins after it.
| Start | What happens | Next start |
|---|---|---|
| 0 | Branch 0: 4 collected, 3 paid, 1 left. Branch 1: 3 in the vault, but 5 is needed, so the van fails | 2 |
| 2 | Branches 2, 3, 4, 5, 0 and 1 all leave enough: the vault holds 6, 5, 4, 6, 6, 5 before paying | none, the ring is complete |
The first start that works is branch 2.
Input: deposits = [4,2,6,1,3,5], payouts = [3,5,2,4,2,3], cap = 5
Output: -1With a vault of 5, the van loses cash at the branch with 6 units, and it runs short later. No start works, so the answer is -1.
Input: deposits = [3,3,3], payouts = [3,3,3], cap = 3
Output: 0At every branch the van collects 3 and pays 3, so it never runs short. Branch 0 works.
1 ≤ len(deposits) ≤ 100,000, len(payouts) = len(deposits), and every deposit and payout is between 0 and 1,000,0000 ≤ cap ≤ 1,000,000,000Driving the whole ring from every branch costs about 100,000 times 100,000 steps, which is 10,000,000,000. When a trip fails, every start up to the failing branch can be skipped. Every branch is then visited a small number of times, so the work is about 200,000 steps.