I have a small problem solving the Car fueling problem using the Greedy Algorithm.
Problem Introduction
You are going to travel to another city that is located miles away from your home city. Your car can travel at most miles on a full tank and you start with a full tank. Along your way, there are gas stations at distances stop1, stop2, ... , stopN from your home city. What is the minimum number of refills needed?
Input:
950
400
4
200 375 550 750
Output:
2
What I've tried as of now
def car_fueling(dist,miles,n,gas_stations):
num_refill, curr_refill, last_refill = 0,0,0
while curr_refill <= n:
last_refill = curr_refill
while (curr_refill <= n-1) & (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles):
curr_refill += 1
if curr_refill == last_refill:
return -1
if curr_refill <= n:
num_refill += 1
return num_refill
What is the problem I'm facing
In the statement
while (curr_refill <= n-1) & (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles)
I am getting the error IndexError: list index out of range
. It is because of gas_stations[curr_refill + 1]
. So when I try to separate it as a while
loop and an if
statement as in
while (curr_refill <= n-1):
if (gas_stations[curr_refill + 1] - gas_stations[last_refill] <= miles):
curr_refill += 1
else:
break
It is entering an infinite loop.
Can you kindly point out the mistake I'm facing?