Skip to content

Latest commit

 

History

History
24 lines (20 loc) · 500 Bytes

134. Gas Station.md

File metadata and controls

24 lines (20 loc) · 500 Bytes
class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int total = 0;
        for (int i = 0; i < gas.size(); ++i)
            total += gas[i] - cost[i];
        if (total < 0) return -1;
        
        int cur = 0, ans = 0;
        for (int i = 0; i < gas.size(); ++i) {
            cur += gas[i] - cost[i];
            if (cur < 0) {
                cur = 0;
                ans = i + 1;
            }
        }
        return ans;
    }
};