Java O(N) Solution that beats 90%


  • 1
    public class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            int startPoint = 0;
            int sum = 0;
            int totalLeftGas = 0;
            for (int i = 0; i < gas.length; i++) {
                int diff = gas[i] - cost[i];
                totalLeftGas += diff;
                sum += diff;
                if (sum < 0) {
                    startPoint = i + 1;
                    sum = 0;
                }
            }
            return totalLeftGas >= 0 ? startPoint : -1;
        }
    }

Log in to reply
 

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