#134
Gas Station
medium· Greedyruns: 0There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i]. You have a car with an unlimited tank, and it costs cost[i] of gas to travel from the ith station to the next. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas and cost, return the starting station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. The solution, if it exists, is unique.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 366
class Solution:
def canCompleteCircuit(
self, gas: list[int], cost: list[int]
) -> int:
if sum(gas) < sum(cost):
return -1
start = 0
tank = 0
for i in range(len(gas)):
tank += gas[i] - cost[i]
if tank < 0:
start = i + 1
tank = 0
return start
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.