My 8ms O(n) C++ Solution


  • 1
    L
    class Solution {
        public:
            int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
                int index = 0;
                int size = gas.size();
                int total = 0;
                int local = 0;
                for (int i = 0; i < size; i ++) {
                    int amount = gas[i] - cost[i];
                    total += amount;
                    local += amount;
                    if (local < 0) {
                        index = i + 1;
                        local = 0;
                    }
                }
                if (total >= 0)
                    return index;
                else
                    return -1;
            }
    };

Log in to reply
 

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