Sharing my simple and fast java solution


  • 1
    M
    public class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            
            int sum = 0;
            int min = Integer.MAX_VALUE;
            int minIndex = -1;
            
            for (int i=0; i<gas.length; i++){
                sum += (gas[i] - cost[i]);
                if (sum < min){
                    min = sum;
                    minIndex = i;
                }
            }
            
            if (sum < 0)
                return -1;
                
            if (minIndex == gas.length - 1)
                return 0;
            else return minIndex + 1;
        }
    }

  • 1
    S

    Why do you chose the index with minimum(gas[i]-cost[i]) as the start index, though it does not affect the result.


  • 0
    S

    It is the sum, not the individual gas[i]-cost[i], so that you can find the station that hardest to reach, if it is the hardest to reach, then can start from here.


  • 0
    S

    I think the code make use of the condition "The solution is guaranteed to be unique".


Log in to reply
 

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