This is a greedy algorithm problem named as car refueling problem. At first, I'm checking if it is possible to complete the track or not. After this, I am counting the least no of steps by using the greedy method. My approach is: First I am going to the maximum distance I can go with the fuel and then I try to find the point which is the least distance from that maximum point. And then I am counting how many times the loop is running.1
Here is the code
def compute_min_refills(distance , tank , stops):
length , refill = 0,0
stops.append(distance)
z = 0
stops.insert(0,z)
stops.sort()
for i in range(len(stops) - 1):
if stops[i+1] - stops[i] > tank:
return -1
if tank >= distance:
return 0
i = 0
while length < stops[-1]:
array = []
refill += 1
while length + tank >= stops[i]:
array.append(stops[i])
i += 1
if i == len(stops) :
break
length += tank
x = max(array)
if distance <= stops[i-1]:
refill -= 1
if x == stops[-2]:
return refill
return refill