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.
解析
所有g(shù)as之和如果小于cost之和闽晦,那么肯定沒有解決方案窟社。
從頭依次加gas-cost南蹂,如果小于0陈瘦,那么以下一個為開始index矫限。
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
int temp1=0,temp2=0,index=0;
for(int i=0;i<gasSize;i++)
{
temp1+=gas[i]-cost[i];
temp2+=gas[i]-cost[i];
if(temp2<0)
{
temp2=0;
index=i;
}
}
if(temp1>=0)
{
if(index==0&&gas[0]>=cost[0])return 0;
else return (index+1)%gasSize;
}
return -1;
}