当前位置:   article > 正文

Leetcode 134. Gas Station_go语言 leetcode 134. gas station

go语言 leetcode 134. gas station

Problem

There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays gas and cost, return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique

Algorithm

Calculate the value of each point by using val[i] = gas[i] - cost[i]. Then find the start point with the max sum value. Then justify it on the circle until the front node the the start point.

Code

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        slen = len(gas)
        val = [0] * slen
        start, sum_v = 0, 0
        for i in range(slen):
            val[i] = gas[i] - cost[i]
            sum_v = sum_v + val[i]
            if sum_v < 0:
                sum_v = 0
                start = i+1
        if start >= slen:
            return -1
        
        sum_v = 0
        index = start
        for i in range(slen):
            sum_v = sum_v + val[index]
            if sum_v < 0:
                return -1
            index = index + 1
            if index >= slen:
                index = 0
        
        return start
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/493409
推荐阅读
相关标签
  

闽ICP备14008679号