891. Refuel Stops

A bus must cover target kilometres along a straight road starting at kilometre 0. It leaves with startFuel litres and burns exactly one litre per kilometre. Along the road there are charging depots listed in stations, where stations[i] = [position, litres] means depot i is at that kilometre and can hand over litres litres once, all of it at once (depots are not necessarily sorted and several may share a position).

The bus may stop at a depot it has reached, even with an empty tank, and take everything there. Return the smallest number of depot stops needed to reach target, or -1 if that is impossible. Reaching a depot or the target with exactly 0 litres left is allowed.

Example 1

Input:
target = 70startFuel = 10stations = [[8,12],[20,15],[30,25],[3,4],[55,9]]
Output:
4
Explanation:

Using the depots with 12, 15, 25 and 9 litres stretches the range 10 -> 22 -> 37 -> 62 -> 71; the three largest depots give only 10 + 25 + 15 + 12 = 62 < 70, so 4 stops are needed.

Example 2

Input:
target = 25, startFuel = 25, stations = [[5,9]]
Output:
0
Explanation:

The starting fuel already covers all 25 km, so no stop is needed.

Example 3

Input:
target = 60, startFuel = 9, stations = [[10,40],[25,3]]
Output:
-1
Explanation:

The only useful depot is at kilometre 10 but the bus runs dry after 9 km, so the answer is -1.

Constraints

  • 1 ≤ target, startFuel ≤ 109
  • 0 ≤ stations.length ≤ 105
  • 1 ≤ position ≤ 109 and 1 ≤ litres ≤ 109 for every depot; depots may lie beyond target

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 400 msC++ 100 msJava 200 msJavaScript 200 msTypeScript 200 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…