LeetCode(力扣)134. 加油站Python

LeetCode134. 加油站

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/gas-station/description/
LeetCode(力扣)134. 加油站Python_第1张图片

代码

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        cursum = 0
        minfuel = float('inf')
        for i in range(len(gas)):
            rest = gas[i] - cost[i]
            cursum += rest
            if cursum < minfuel:
                minfuel = cursum
        
        if cursum < 0:
            return -1
        if minfuel >= 0:
            return 0

        for i in range(len(gas) - 1, -1, -1):
            rest = gas[i] - cost[i]
            minfuel += rest
            if minfuel >= 0:
                return i
        
class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        cursum = 0
        total = 0
        start = 0

        for i in range(len(gas)):
            cursum += gas[i] - cost[i]
            total += gas[i] - cost[i]
            
            if cursum < 0:
                start = i + 1
                cursum = 0
        if total < 0:
            return -1
        return start

你可能感兴趣的:(leetcode,python,算法,职场和发展)