You have a truck moving around a circular track with gas stations spaced out around the circle. Each station has a finite amount of gas. The gas tank on the truck is infinit
Here is my solution in python. Addition to other explained once we keep a variable to calculate the need for the previous stations and when we are at the end of the array we just check if our leftover is above that need and return accordingly.
if not gas or not cost:
return - 1
index = 0
start = 0
total = 0
need = 0
while index < len(gas):
# If we can travel without any leftover.
# What is our status since start, if total is
# below zero that means we are in a worse situation
# then we were.
total += gas[index] - cost[index]
if total < 0 :
need -= total
start = index + 1
total = 0
index += 1
if total - need >= 0:
return start
else:
return -1