-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgas-station.py
More file actions
38 lines (33 loc) · 1.04 KB
/
gas-station.py
File metadata and controls
38 lines (33 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from typing import List
class Solution:
# Time complexity: O(n)
# Space complexity: O(1)
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
curr, total, res = 0, 0, 0
for i, (g, c) in enumerate(zip(gas, cost)):
total += g-c
curr += g-c
if curr < 0:
curr = 0
res = i+1
if total < 0:
return -1
else:
return res
# Time complexity: O(n^2)
# Space complexity: O(1)
# Time limit exceeded
def canCompleteCircuit2(self, gas: List[int], cost: List[int]) -> int:
# if sum(gas) < sum(cost): return -1
for i in range(len(gas)):
curr = gas[i] - cost[i]
if curr < 0: continue
j = (i+1) % len(gas)
while j != i:
curr += gas[j] - cost[j]
if curr < 0:
break
j = (j+1) % len(gas)
if j == i:
return i
return -1