There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
思想
如果gas总和大于cost总和,那么一定有一种解法。
在知道这个假设的前提下解题并不难,一次遍历,当油量无法达到时更新可能的起始点,最后比较有油和缺油的量即可,关键是如何证明?
当然,可以用严谨的数学公式去推导,不过理解起来总是需要点时间。不妨做个类比,假设你去买东西,手里有3,5,7等不同面值的钞票,商品的价格有4,4,1等等,我们都知道,如果手里钱的总数大于商品价格总数,那自然可以将所有商品都买到(走完),这与本题是不是一个道理?只是提供个想法,正确性可以讨论和验证。
AC代码
//c++
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start=0,tank=0,lack=0;
for(int i=0;i<gas.size();++i)
{
if((tank=tank+gas[i]-cost[i])<0){
start=i+1;lack+=tank;tank=0;
}
}
return tank+lack<0?-1:start;
}
};