Algorithm for truck moving around a circle of gas stations

前端 未结 11 1379
陌清茗
陌清茗 2020-12-13 07:08

You have a truck moving around a circular track with gas stations spaced out around the circle. Each station has a finite amount of gas. The gas tank on the truck is infinit

11条回答
  •  一向
    一向 (楼主)
    2020-12-13 07:44

    starting from any station, try to move to the next one (to the right). If you can't (run out of gas), we have to take gas from the left of the starting point (move starting station to the left).

        start = 0
        end = start
        amount = 0
        for i in range(n):
            if amount > 0:
                amount += (gas[end] - cost[end])
                end = (end + 1) % n
            else:
                start = (start - 1 + n) % n
                amount += (gas[start] - cost[start])
    
        if amount >= 0: return start    
        return -1
    

    `

提交回复
热议问题