Simple Java Solution


  • 1
    Z
    public class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            if (gas == null || cost == null || gas.length != cost.length) {
                return -1;
            }
    
            int total = 0, sum = 0, start = 0;
            for (int i = 0; i < gas.length; i++) {
                total += gas[i] - cost[i];
                sum += gas[i] - cost[i];
                if (sum < 0) {
                    sum = 0;
                    start = i+1;
                }
            }
            return total < 0 ? -1 : start;
        }
     
    }
    

Log in to reply
 

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