leetcode 134. Gas Station

题目链接:leetcode

思路:
贪婪

1
2
3
4
5
6
7
8
9
class Solution(object):
def canCompleteCircuit(self, gas, cost):
n = len(gas)
dp = [gas[0] - cost[0]]
for i in range(1,n):
dp.append(dp[-1] + gas[i] - cost[i])
if dp[-1] < 0:
return -1
return (dp.index(min(dp)) + 1 )%n

一个更清晰的solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
start, cur_sum, total_sum = 0, 0, 0

for i in range(len(gas)):
diff = gas[i]-cost[i]
cur_sum += diff
total_sum += diff

if cur_sum < 0:
start = i+1
cur_sum = 0

if total_sum >= 0:
return start
return -1