My O(N) 8ms C++ Solution


  • 0
    D
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int candidate = -1;
        int netGain = 0;
        int prevGain = 0;
        for (int i = 0; i < gas.size(); i++) {
            if (candidate == -1) {
                candidate = i;
                prevGain += netGain;
                netGain = gas[i] - cost[i];
            } else {
                netGain += (gas[i] - cost[i]);
            }
            
            if (netGain < 0) {
                candidate = -1;
            }
        }
        
        if (netGain + prevGain >= 0) {
            return candidate;
        } else {
            return -1;
        }
    }

Log in to reply
 

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