My Java solution


  • 0
    I

    when ever the sum of money is negative, go backwards until finding a new starting point

    public class Solution {
    int money = 0;
    int current = 0;
    int startIndex = 0;
    int endIndex;
    public int canCompleteCircuit(int[] gas, int[] cost) {
    endIndex = gas.length;
    while(current < endIndex){
    money += gas[current] - cost[current];
    if(money < 0 ){
    int backwordIndex = startIndex;
    while( money < 0 ){
    backwordIndex = decrementIndex(backwordIndex, gas.length);
    if(backwordIndex == current){
    return -1;
    }
    money += gas[backwordIndex] - cost[backwordIndex];
    }
    startIndex = backwordIndex;
    endIndex = backwordIndex;
    }
    current ++;

        }
        return startIndex;
    }
    
    private int decrementIndex(int index, int length){
        if(index == 0){
            index = length-1;
        }
        else{
            index --;
        }
        return index;
    }
    

    }


Log in to reply
 

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