Created
November 27, 2020 04:26
-
-
Save Irene-123/036b6ddad985c63af50514fe71a217f4 to your computer and use it in GitHub Desktop.
The car Fueling problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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