Last active
April 6, 2019 16:55
-
-
Save DiegoGallegos4/dc135c38c42f93bb35cf03843d886dd3 to your computer and use it in GitHub Desktop.
Greedy implementation of Max Refills Problem
This file contains 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 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