1695. Cheapest Fuel Run

A delivery car starts with an empty tank at station 0 and drives to station n-1, where n = price.length. Each step between consecutive stations burns exactly one litre. Station j sells fuel at price[j] per litre, and the tank holds at most capacity litres. The litre burnt on step t (from station t to station t+1) can have been bought at any station from t - capacity + 1 to t (never before station 0). Return the minimum total cost of all fuel bought, as a long. Scanning every window costs O(n * capacity), which is too slow; use a monotonic deque to finish in O(n) time and O(n) space.

Example 1

Input:
price = [4,2,7,3,5], capacity = 2
Output:
11
Explanation:

The four steps buy from the cheapest station among the last two: 4, 2, 2 and 3, so the cost is 11.

Example 2

Input:
price = [4,2,7,3,5], capacity = 1
Output:
16
Explanation:

With a one-litre tank every step uses fuel bought at its own start station: 4 + 2 + 7 + 3 = 16.

Example 3

Input:
price = [4,2,7,3,5], capacity = 4
Output:
10
Explanation:

With a tank of 4 the cheap price 2 from station 1 serves steps 1, 2 and 3: 4 + 2 + 2 + 2 = 10.

Constraints

2 ≤ price.length ≤ 2 * 105

1 ≤ capacity ≤ price.length

1 ≤ price[j] ≤ 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 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(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…