simple idea C++


  • 0
    C
    class Solution {
    public:
        int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
            int l = gas.size();
            vector<int> a(l);
            for (int i = 0; i < l; ++i){
                a[i] = gas[i] - cost[i];
            }
            int i = 0, j = l-1, s = a[0];
            int ans = 0;
            while (i < j){
                while (i < j && s >= 0) s += a[++i];
                while (i < j && s < 0) s += a[j--];
            }
            
            return s >= 0 ? (j+1) % l : -1;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.