LeetCode134. 加油站
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/gas-station/description/
代码
class Solution:def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:cursum = 0minfuel = float('inf')for i in range(len(gas)):rest = gas[i] - cost[i]cursum += restif cursum < minfuel:minfuel = cursumif cursum < 0:return -1if minfuel >= 0:return 0for i in range(len(gas) - 1, -1, -1):rest = gas[i] - cost[i]minfuel += restif minfuel >= 0:return i
class Solution:def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:cursum = 0total = 0start = 0for i in range(len(gas)):cursum += gas[i] - cost[i]total += gas[i] - cost[i]if cursum < 0:start = i + 1cursum = 0if total < 0:return -1return start