Skip to content

Instantly share code, notes, and snippets.

@priyankvex
Last active May 6, 2019 17:36
Show Gist options
  • Save priyankvex/e8f1753a028fbd6533cf6e8d878b7fb5 to your computer and use it in GitHub Desktop.
Save priyankvex/e8f1753a028fbd6533cf6e8d878b7fb5 to your computer and use it in GitHub Desktop.
Gas station completing the circuit
"""
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