Making a DP Faster & the Refuel Plan
In short: a DP transition that scans a sliding window for a minimum
(cost[i] = fees[i] + min(cost[i − reach..i − 1])) does the same comparisons
over and over, because consecutive windows mostly overlap. A monotonic
deque fixes it by keeping only candidates that could still win: anything
older and no cheaper than a newer arrival can never be the answer again,
so it's evicted for good. What's left increases front to back, the cheapest
always at the front, and every station is pushed once and popped at most
once — O(1) amortised per station instead of O(reach).

Meridian's long-haul van crosses the region on a road lined with fuel stations.
Each one charges a different stop fee, and the tank only reaches so far, so
consecutive stops can be at most reach stations apart. The van has to stop at
the first station and the last. Which stations should it use?
You already know how to write this DP:
cost[i] = fees[i] + min(cost[i − reach], …, cost[i − 1])
It's correct, and it scans up to reach cells for every station. On a
route with 200,000 stations and a reach of 500 that's 100 million reads for
one plan, and dispatch wants to re-plan every time a price changes. This
lesson doesn't find a new DP. It takes a DP you already have and makes the
inner loop disappear.
Where the time goes
Count the reads the scan makes on a short route:
reads = 0
n, reach = 10, 3
for i in range(1, n):
for j in range(max(0, i - reach), i):
reads += 1
print(reads)Look at what consecutive stations actually scan. Station 5 looks at 2, 3, 4.
Station 6 looks at 3, 4, 5. The window slides forward by one: one station
leaves at the back, one arrives at the front, and the other reach − 1 are
the same stations as last time. The scan throws away everything it learned and
starts again, every time.