1757. Refuel Along the Highway

Hard7.5 points estimatedGreedyMonotonic StackHeap

A delivery truck drives along a straight highway from position 0 to position target, burning exactly one unit of fuel per unit of distance. Its tank holds at most capacity units, and it begins at position 0 with a full tank that costs nothing. Fuel stations are listed by positions (non-decreasing; several stations may share a position) with prices[i] being the cost of one unit at station i. At any station the truck may buy any whole number of units as long as the tank never exceeds capacity. Return the minimum total money needed to reach target as a long, or -1 if it is impossible. Aim for O(n log n) time (O(n) after sorting) and O(n) space. There are up to 10^5 stations; target and capacity are at most 10^9.

Example 1

Input:
positions = [2,4,7,9]prices = [5,3,6,2]capacity = 6target = 12
Output:
15
Explanation:

The free tank covers the first stretch; buy 3 units at position 4 (price 3) for 9 and 3 units at position 9 (price 2) for 6, for a total of 15.

Example 2

Input:
positions = [3]prices = [4]capacity = 2target = 10
Output:
-1
Explanation:

The first station at position 3 is farther than a full tank of 2 can reach, so the target cannot be reached and the answer is -1.

Constraints

1 ≤ n = positions.length = prices.length ≤ 105; 0 ≤ positions[i] ≤ target and positions is non-decreasing; 1 ≤ prices[i] ≤ 104; 1 ≤ capacity, target ≤ 109.

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 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,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…