8ms simple O(n) c++ solution


  • 4
    Z
    class Solution {
    public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int idx = -1, total = 0, maxn = -1;
        for(int i = cost.size()-1; i >= 0; --i)
        {
            total += gas[i] - cost[i];
            if(total > maxn)
            {
                idx = i;
                maxn = total;
            }
        }
        return total>=0?idx:-1;
    }
    };

Log in to reply
 

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