There are N gas stations along a circular route, where the amount of gas at stationi isgas[i].

You have a car with an unlimited gas tank and it costscost[i]of gas to travel from stationi 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

百度题号,说到是最大序列的变形,然后自己想:

最大序列咋求的?从开头开始算累加和,发现小于0,前面都不要了,从当前位置重新加和,因为某段和是负数说明这段不会对于最大序列做贡献。

这个题也一样,某段如果是负数说明放结尾,要么就是根本没有可行解。

从0开始(这点我得吐槽一下,leetcode什么玩意,连个示例都没有,都不知道0开始还是1开始)

三个变量pos,sum,tmp分别表示开始点,总和,当前段的和。

如果发现某一段和是负数就清零tmp,pos换成下一个点

最后不要忘记sum+=tmp

判断sum值是否大于等于0

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int num=gas.size();
        int sum=0,tmp=0;
        int pos=0;
        for(int i=0;i<num;i++)
        {
        	tmp+=gas[i];
            tmp-=cost[i];
            if(tmp<0) {pos=i+1;sum+=tmp;tmp=0;}
        }
        sum+=tmp;
        if(sum>=0)return pos;
        else return -1;
    }
};