Elegant Java Solution


  • 3
    M
    public int canCompleteCircuit(int[] gas, int[] cost) {
    
    	int start = 0, count = 0, cur = 0, n = gas.length;
    
    	while (count < n && start < 2 * n) {
    		cur += gas[start % n] - cost[start % n];
    		if (cur < 0) {
    			count = 0;
    			cur = 0;
    		} else {
    			count++;
    		}
    		start++;
    	}
    
    	return count < n ? -1 : start % n;
    }

  • 0
    M

    could you tell me why this is correct?


  • 0
    R

    excellent! thanks for sharing


  • 0
    R

    @myanonymos 'start' is the variable for starting gas station and for every 'start' between 0~N it will go another N stations to check. That's why he use 2 * N.
    You can actually debug it.


Log in to reply
 

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