Skip to content

Commit 7c38239

Browse files
authored
Merge pull request neetcode-gh#511 from johan456789/patch-1
use the code shown in video
2 parents acf3ef7 + e4b33cc commit 7c38239

File tree

2 files changed

+24
-22
lines changed

2 files changed

+24
-22
lines changed

134-Gas-Station.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
class Solution:
22
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
3-
start, end = len(gas) - 1, 0
4-
total = gas[start] - cost[start]
3+
if sum(gas) < sum(cost):
4+
return -1
5+
6+
res = 0
7+
total = 0
8+
for i in range(len(gas)):
9+
total += gas[i] - cost[i]
10+
11+
if total < 0:
12+
total = 0
13+
res = i + 1
514

6-
while start >= end:
7-
while total < 0 and start >= end:
8-
start -= 1
9-
total += gas[start] - cost[start]
10-
if start == end:
11-
return start
12-
total += gas[end] - cost[end]
13-
end += 1
14-
return -1
15+
return res

python/134-Gas-Station.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
class Solution:
22
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
3-
start, end = len(gas) - 1, 0
4-
total = gas[start] - cost[start]
3+
if sum(gas) < sum(cost):
4+
return -1
5+
6+
res = 0
7+
total = 0
8+
for i in range(len(gas)):
9+
total += gas[i] - cost[i]
10+
11+
if total < 0:
12+
total = 0
13+
res = i + 1
514

6-
while start >= end:
7-
while total < 0 and start >= end:
8-
start -= 1
9-
total += gas[start] - cost[start]
10-
if start == end:
11-
return start
12-
total += gas[end] - cost[end]
13-
end += 1
14-
return -1
15+
return res

0 commit comments

Comments
 (0)