I have an array of n
service stations D[]
on a highway such that D[i]
is the distance of the station i
from the start of the highway.
I also have an array of costs C[]
such that C[i]
is the cost of getting my vehicle serviced at station i
.
I have to get my car serviced at the first station, and my car can travel at most 100 miles between stations.
What is the most efficient algorithm to get from the start of the highway to the end with the least cost (I need to know which stations to stop at)? I was able to find a greedy solution for minimizing the number of stops, but for the least cost, I am thinking DP, with the optimal subproblem:
bestcost[j] = min( 0<i<j bestcost[i] + C[j] s.t. D[j]-D[i] <= 100)
and have a separate array last[j]
which contains the last station at which to stop, which would be the best i
from above subproblem.
Would this be the right approach, or is there a better Greedy / DP solution?
O(n)
with a monotonic queue that allows you to find the min inO(1)
, which is optimal and also has a low constant factor. That even works if the range of your bike is not constant. – TillionC[i]
every time I stop at a given stationi
. – TropoC[i] > C[j] where i > j
, this is where you will stop at every station on the road – Contei
that you either pay (in which case your gas is filled and you payC[i]
) or you don't (in which case your gas is not filled and you pay 0). – Tillionbestcost[i]
is the minimal cost to arrive atD[i]
AND have a service at stationi
. Obviously you HAVE to payC[i]
if you decide to do that. But that doesn't mean that this subresult is ever used, so in particular it does NOT mean that we use the station in a globally optimal solution. Do you have experience with dynamic programming? – Tillionbestcost[j] = min( 0<i<j bestcost[i] + C[j] s.t. D[j]-D[i] <= 100)
starting from station 0 .. you have one path, it's linear and deterministic, the operationmin(bestcost[i]+C[j])
is equivalent tomin(C[j])
– Contej
is constant if you computebestcost[j]
, somin(C[j])
does make no sense at all. "the operationmin(bestcost[i]+C[j])
is equivalent tomin(C[j])
" ist just wrong, you iterate over the arraybestcost[j]
for the reachable stations and take the minimum, then you addC[j]
because you decided to stop atj
. "you have one path, it's linear and deterministic" Well the resulting path could look like this: Stop at station 1, skip station 2, skip station 3, stop at 4, stop at 5, skip 6, stop at 7. What do you mean by "linear and deterministic"? – Tillionbestcost[j] = min(0<i<j bestcost[i] + C[j] s.t. D[j]-D[i] <= 100)
If you can't see that, I have to doubt your ability to read code... – Tillion