One loop solution. Java.


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

Log in to reply
 

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