LeetCode(力扣)134. 加油站Python

LeetCode134. 加油站

题目链接

https://leetcode.cn/problems/gas-station/description/
在这里插入图片描述

代码

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

猜你喜欢

转载自blog.csdn.net/qq_44953660/article/details/132865673