Ride-hailing app~35 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-871greedy · heaps
A ride-hailing app plans an electric ride along a long road, from distance 0 to a destination at distance target. The car can cover as many kilometres as it has charge units. Along the road there are charging stations, each at a distance from the start.
At a station the driver may stop and add that station's whole charge, and every stop costs time. Your team lead says: "Show the fewest stops that get the car to the destination." A road can have 100,000 stations, and the driver may decide at any time which stations to use.
Write fewest_charging_stops(target, start_charge, stations).
start_charge units. One unit moves it one kilometre.stations[i] is [position, charge], sorted by position. The car can stop at a station only if it can reach the position. A stop adds charge units, and the units are never lost.target. It is 0 when the start charge is enough, and -1 when the destination cannot be reached.Input: target = 30, start_charge = 8, stations = [[4, 6], [7, 3], [12, 10], [18, 5], [23, 9]]
Output: 3Keep the range, the distance the car can cover, which starts as 8. Visit the stations in order, and the destination last. Keep the charges of the stations already passed in a max-heap. When the next point is out of range, pretend you stopped at the passed station with the most charge.
| Next point | Range before | Pretended stop (charge) | Range after | Stops | Heap after adding this point |
|---|---|---|---|---|---|
| 4 | 8 | none | 8 | 0 | 6 |
| 7 | 8 | none | 8 | 0 | 6, 3 |
| 12 | 8 | 6 | 14 | 1 | 10, 3 |
| 18 | 14 | 10 | 24 | 2 | 5, 3 |
| 23 | 24 | none | 24 | 2 | 9, 5, 3 |
| 30 (destination) | 24 | 9 | 33 | 3 | 5, 3, 0 |
The answer is 3 stops: the stations at 4, 12 and 23.
Input: target = 100, start_charge = 10, stations = [[20, 5]]
Output: -1The only station is at distance 20, and the car can cover only 10.
Input: target = 20, start_charge = 20, stations = [[5, 5]]
Output: 0The start charge reaches the destination, so no stop is needed.
1 ≤ target ≤ 10^9, and 0 ≤ start_charge ≤ 10^90 ≤ length of stations ≤ 10^5, each station is [position, charge] with 1 ≤ position < target and 0 ≤ charge ≤ 10^9Choosing a set of stations to stop at gives 2^n sets. A table over the number of stops and the stations costs n² steps, which is 10^10 for n = 100,000.
A heap of the passed stations gives the best one in log n steps. The range is below target before a charge is added, and a charge is at most 10^9. So it stays below 2 × 10^9 and fits a 32-bit integer.