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個圈里面有N個汽油站,i站的汽油有gas[i]汽油。現(xiàn)在有1輛無窮容量油箱的車,它從i站開到(i+1)需要耗費cost[i]汽油。如果這輛車可以走完這個圈,那末返回這個車的出發(fā)點,否者返回⑴.
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int start=0,tank=0,total=0;
for(int i=0;i<gas.size();i++)
{
tank+=gas[i]-cost[i];
if(tank<0)
{
total+=tank;
tank=0;
start=i+1;
}
}
return ((total+tank)<0)?-1:start;
}
};