[leetcode_134] Gas Station

100 problems done! A small milestone to celebrate.
First, check whether a feasible solution exists.
Then start from each node and find the first one that can reach the end.
Got AC. I believe the approach is correct, but I’m not 100% certain.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int ans = -1;
        int sum = 0;
        for(int i = 0;i < gas.size();i++) {
            sum += gas[i];
            sum -= cost[i];
        }
        if(sum < 0)return ans;

        int now = 0;
        int i = 0;
        ans = 0;
        while(i < gas.size()) {
            now += gas[i] - cost[i];
            if(now < 0) {
                i++;
                now = 0;
                ans = i;
            }
            else
                i++;
        }
        return ans;
    }
};