Skip to the code
cf.
+50 XP

#594 Fewest Recharge Stops

hard

A trip planner for an electric scooter must reach target kilometers away. The scooter starts with startCharge units of charge and uses 1 unit per kilometer. Charging stations are listed in stations as [position, charge], sorted by position: stopping there adds charge units (the battery has no limit).

Write fewestStops(target, startCharge, stations) that returns the fewest charging stops needed to reach target, or -1 if it can't be reached. Arriving somewhere with exactly 0 charge left still counts as arriving.

Example 1

Input: target = 100, startCharge = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2

Stop at 10 (charge 60, reach 70), then at 60 (charge 40, reach 110).

Example 2

Input: target = 100, startCharge = 1, stations = [[10,100]]
Output: -1

The scooter can't even reach the first station.

Constraints

  • 1 <= target, startCharge <= 10^9
  • 0 <= stations.length <= 500
  • 0 < position < target, positions increase
  • 1 <= charge <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).