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
Solution
枚举所有可能, 并通过寻找规律来去除冗余计算.
我们发现:
如果选择站点i
作为起点「恰好」无法走到站点j
,那么i
和j
中间的任意站点k
都不可能作为起点.
证明:
假设tank
记录当前油箱中的油量,如果从站点i
出发(tank = 0
),走到j
时恰好出现tank < 0
的情况,那说明走到i, j
之间的任意站点k
时都满足tank >= 0
.
Given sequence:
此外, j
是第一个恰好出现tank < 0
的点, 必定有gas[j-1] - cost[j-1] < 0
. 否则有gas[j] - cost[j] >= 0
且tank[j]<0
, 此时点j-1满足:
1 | tank[j-1] = tank[i] - (gas[j-1] - cost[j-1] ) <= tank[j] < 0 |
与前提矛盾.
因此, 下一个可能的起始站点是j+1
.
Code
如果总油量小于总的消耗, 那么起点从0一直遍历到N-1都不符合条件. 因此预先排除掉这个无解的情况.
1 | public int canCompleteCircuit(int[] gas, int[] cost) { |
- Complexity:
. = number of gas stations.