Charging Stops on an EV Route
Electric-car drivers ask the maps app for a route and want to know, before they leave, how many times they will have to stop and charge. Every stop costs them half an hour, so the app should plan as few as possible.
The route is a straight road from kilometre 0 to kilometre distance. The car leaves with a full battery, which lasts batteryRange kilometres. Charging stations stand at the kilometre marks in stations, in no particular order (two stations can share a position). At a station the car can charge back to full.
Return the fewest charging stops needed to reach kilometre distance, or -1 if it cannot be reached at all. Arriving with an empty battery, exactly at a station or at the destination, is fine.
Example
distance = 100, batteryRange = 40, stations = [30, 60, 90].
On a full battery the car reaches kilometre 40, so it must stop at the station at 30. From there it reaches 70, so it stops again at 60, and from 60 it reaches 100. The answer is 2.
[ "100", "40", "[30,60,90]" ]
Explanation. The example.
[ "50", "60", "[]" ]
Explanation. The battery covers the whole route.
[ "100", "30", "[20,50,80]" ]
Explanation. Every station is needed.
[ "100", "30", "[20,55,80]" ]
Explanation. From kilometre 20 the car reaches 50, and the next station is at 55.
[ "120", "50", "[90,40,40,70,10]" ]
Explanation. Unsorted, with a duplicate: stop at 40, then at 90.
[ "60", "30", "[30]" ]
Explanation. Arriving at a station with an empty battery is fine.
[ "30", "30", "[]" ]
Explanation. Arriving at the destination with an empty battery is fine.
[ "10", "5", "[5,5,5]" ]
Explanation. Three stations at the same place count as one stop.
[ "1000", "200", "[150,300,340,520,700,760,880,990]" ]
Explanation. Always charging at the farthest reachable station.
[ "100", "10", "[20]" ]
Explanation. The first station is out of reach.
[ "1000000000", "600000000", "[500000000]" ]
Explanation. Large distances.
Follow-up: Stations now charge at different speeds, and the driver wants the least total time spent charging rather than the fewest stops. Does the greedy choice still work? What would you use instead?
- `1 <= distance <= 10^9` - `1 <= batteryRange <= 10^9` - `0 <= stations.length <= 10^5` - `0 < stations[i] < distance`
- Views
- 3