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.
思路:这道题可以基于最大字数列和的思想来解题,每次循环累加和存油量与耗油量只差分别记录两次,如果这次循环的差和小于零,则start记录这个点的下一个,并且将上述的其中一个变量置零,进行下次循环。如果循环下来,上述差额的累加和小于零的话,说明无法完成旅程。反之,返回start,记为开始旅程的起点。
class Solution { public: int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { if(gas.size()==0) return 0; int sum=0; int diff_sum=0; int result=0; for(int i=0;i<gas.size();i++) { sum+=gas[i]-cost[i]; diff_sum+=gas[i]-cost[i]; if(sum<0) { result=(i+1)%gas.size(); sum=0; } } if(diff_sum<0) return -1; return result; } };