make the full circular path, shortest path exercise?

后端 未结 8 1509
耶瑟儿~
耶瑟儿~ 2021-02-04 22:27

I got this question in an interview and I was not able to solve it.

You have a circular road, with N number of gas stations. You know the ammount of gas

8条回答
  •  攒了一身酷
    2021-02-04 23:06

    While trying each start station of course works fine, it takes quadratic time, while there is a simple linear-time algorithm.

    Use a magic car that can keep going if the fuel level runs into the negative. Start at an arbitrary station and do a full tour, visiting every station. If you return with less than zero fuel, there is no solution. Otherwise, the best station to start is the one where the fuel level on arrival was lowest.

    This works because the fuel levels of all possible tours are identical except for a constant offset.

提交回复
热议问题