Problem 310711 · hard · Phase 03 Linear Management & Searching

Fewest Fuel Stops

greedy · heap · reachability

A truck must drive target kilometres, burning one litre per kilometre, and starts with fuel litres. stations[i] = [position, litres] lists fuel stations sorted by position; stopping at a station adds its litres (the tank has no limit). The truck can reach a station or the target with exactly zero litres left. Return the minimum number of stops needed to reach the target, or -1 if it is impossible.

Examples

Input:  target = 120, fuel = 25, stations = [[15, 20], [30, 50], [50, 10], [80, 60], [90, 5]]
Output: 3
Explanation: Stop at 15 (fuel reaches 45), at 30 (95) and at 80 (155 >= 120).
Input:  target = 50, fuel = 50, stations = []
Output: 0

Constraints

  • 1 <= target <= 10**9, 0 <= fuel <= 10**9, 0 <= len(stations) <= 5 * 10**4.
  • 0 < position < target, 1 <= litres <= 10**9; positions strictly increase.
  • Target complexity: O(n log n).

Goals

  • Defer the decision of where to stop until a stop becomes necessary
  • Use a max-heap of passed stations to pick the most valuable one
Starting Python…