Skip to content

Instantly share code, notes, and snippets.

@DiegoGallegos4
Last active April 6, 2019 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DiegoGallegos4/dc135c38c42f93bb35cf03843d886dd3 to your computer and use it in GitHub Desktop.
Save DiegoGallegos4/dc135c38c42f93bb35cf03843d886dd3 to your computer and use it in GitHub Desktop.
Greedy implementation of Max Refills Problem
def min_refills(stations, full_tank_limit):
"""
Find min refills for gas tank in a trip between point A and B
Args:
stations (array): possible gas stations to refill including start(A) and end(B).
full_tank_limit (int): gas tank maximum limit.
Returns:
(int) number of refills needed to make the trip between A -> B
Running time: O(n)
current_ref ranges between 0 and n - 1 so the outer and inner loop
does not actually multiply (n * n = O(n^2)).
"""
current_refill, num_refills = 0, 0
n = len(stations) - 1
while current_refill < n:
last_refill = current_refill
while (
current_refill < n
and stations[current_refill + 1] - stations[last_refill] <= full_tank_limit
):
current_refill += 1
if current_refill == last_refill:
return -1
if current_refill < n:
num_refills += 1
return num_refills
# Example
stations = [0, 200, 375, 550, 750, 950]
max_lim = 400
min_refill(stations, max_lim) # --> 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment