Ride-hailing app~15 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-134greedy
You work on a ride-hailing app that runs electric shuttles. One shuttle drives a circular route with n stops, numbered from 0. At stop i it can take charge[i] units of battery, and the drive from stop i to the next stop uses usage[i] units.
The shuttle starts with an empty battery at the stop you choose. Your team lead asks: "Which stop can we start from to drive the full loop without running out?"
Write start_stop(charge, usage).
charge[i] units, and then drives to the next stop, which uses usage[i] units. The route is a circle, so stop n - 1 is followed by stop 0.Input: charge = [4, 2, 7, 1, 3], usage = [3, 5, 4, 2, 2]
Output: 2Look at the gain at each stop, charge[i] - usage[i]: 1, -3, 3, -1, 1. Keep a battery from a candidate start. When it goes below 0, no stop up to here can be the start, so try the next stop with an empty battery.
| Stop | Gain | Battery from the candidate | Candidate start | Total gain |
|---|---|---|---|---|
| 0 | 1 | 1 | 0 | 1 |
| 1 | -3 | -2: reset | 2 | -2 |
| 2 | 3 | 3 | 2 | 1 |
| 3 | -1 | 2 | 2 | 0 |
| 4 | 1 | 3 | 2 | 1 |
The total gain is 1, which is not negative, so the loop is possible. The candidate start is 2.
Input: charge = [2, 3, 4], usage = [3, 4, 3]
Output: -1The total charge is 9 and the total usage is 10. The shuttle cannot make the full loop from any stop.
Input: charge = [1, 3, 0], usage = [0, 1, 3]
Output: 0From stop 0 the battery goes 1, then 3, then 0, and the shuttle arrives back with an empty battery. That is allowed, and stop 0 is the smallest stop.
1 ≤ n ≤ 100,000, and charge and usage both have n numbers0 ≤ charge[i], usage[i] ≤ 10,000There are up to 100,000 stops. Trying every start and driving the whole loop from each costs n^2, which is 10 billion steps. One pass with a running battery costs 100,000 steps. The totals stay within 10^9 either way, so a normal integer is enough.