Concise Java Solution


  • 2
    S

    This question can be convert into "Find the biggest sum subsequence in gas[i]-cost[i]".
    Furthermore if sum(gas) - sum(cost) <0, returns -1.

       public class Solution {
            public int canCompleteCircuit(int[] gas, int[] cost) {
                int sum = 0, start = 0, S = gas[0] - cost[0];
                for(int i=0;i<gas.length;i++){
                    int an = gas[i] - cost[i];
                    sum += an;
                    if((S + an) < an){
                        S = an;
                        start = i;
                    }else
                        S += an;
                }
                if(sum < 0) start = -1;
                return start;
            }
        }

Log in to reply
 

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