Last active
May 6, 2019 17:36
-
-
Save priyankvex/e8f1753a028fbd6533cf6e8d878b7fb5 to your computer and use it in GitHub Desktop.
Gas station completing the circuit
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
""" | |
https://scammingthecodinginterview.com | |
Week 3: Greedy | |
Problem: 2 | |
""" | |
class Solution(object): | |
def solve(self, fuel, cost): | |
n = len(fuel) | |
end = 0 | |
start = n - 1 | |
sum = fuel[start] - cost[start] | |
while start > end: | |
if sum >= 0: | |
sum = sum + fuel[end] - cost[end] | |
end+=1 | |
else: | |
start -= 1 | |
sum += fuel[start] - cost[start] | |
return start if sum >= 0 else -1 | |
if __name__ == "__main__": | |
fuel = [1, 2, 3, 4, 5] | |
cost = [3, 4, 5, 1, 2] | |
ans = Solution().solve(fuel, cost) | |
print(ans) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment