Algorithm for truck moving around a circle of gas stations

前端 未结 11 1376
陌清茗
陌清茗 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 08:03

    Here is my solution in python. Addition to other explained once we keep a variable to calculate the need for the previous stations and when we are at the end of the array we just check if our leftover is above that need and return accordingly.

        if not gas or not cost:
            return - 1
    
        index = 0
        start = 0
        total = 0
        need = 0
        while index < len(gas):
            # If we can travel without any leftover.
            # What is our status since start, if total is
            # below zero that means we are in a worse situation
            # then we were.
            total += gas[index] - cost[index]
            if total < 0 :
                need -= total
                start = index + 1
                total = 0
            index += 1
    
        if total - need >= 0:
            return start
        else:
            return -1
    

提交回复
热议问题