์ฃผ์œ ์†Œ - leetcode 81๋ฒˆ

๋ฌธ์ œ

134. Gas Station

ํ•ด์„ค

  • ๋ฌธ์ œ์—์„œ ์กฐ๊ฑด์„ ๋น ๋œจ๋ฆฌ๊ณ  ์ œ๋Œ€๋กœ ์œ ๋„ํ•ด๋‚ด์ง€ ๋ชปํ•ด์„œ ๊ฝค ํ—ค๋งธ์Œ
  • ์กฐ๊ฑด์—์„œ ๋‹ต์ด ๋ช…ํ™•ํžˆ ์ •ํ•ด์ง€์ง€ ์•Š๊ณ  ์—ฌ๋Ÿฌ๊ฐœ๋กœ ๋‚˜์˜จ๋‹ค๋ฉด ๋ฐ˜๋Œ€๋กœ ๋ถ€์ •ํ•ด์„œ if ์กฐ๊ฑด์„ ์„ธ์›Œ์ฃผ๋ฉด ์˜์™ธ๋กœ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐ๋  ์ˆ˜ ๋„ ์žˆ์Œ

ํ’€์ด

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas) < sum(cost):
            return -1
        tank = 0
        result = 0
        for i in range(len(gas)):
            tank += gas[i] - cost[i]
            if tank < 0:
                tank = 0
                result = i + 1
        return result