Skip to content

Instantly share code, notes, and snippets.

@Irene-123
Created November 27, 2020 04:26
Show Gist options
  • Save Irene-123/036b6ddad985c63af50514fe71a217f4 to your computer and use it in GitHub Desktop.
Save Irene-123/036b6ddad985c63af50514fe71a217f4 to your computer and use it in GitHub Desktop.
The car Fueling problem
def car_fueling(dist,miles,n,gas_stations):
num_refill, curr_refill, limit = 0,0,miles
while limit < dist:
# While the destination cannot be reached with current fuel
if curr_refill >= n or gas_stations[curr_refill] > limit:
# Cannot reach the destination nor the next gas station
return -1
# Find the furthest gas station we can reach
while curr_refill < n-1 and gas_stations[curr_refill+1] <= limit:
curr_refill += 1
num_refill += 1 # Stop to tank
limit = gas_stations[curr_refill] + miles # Fill up the tank
curr_refill += 1
return num_refill
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment