Share my Java concise solution and thoughts


  • 1
    J

    Actually, you can take gas and cost as a line chart, gas as upward segments while cost as downward ones. They just appear one by one like:

          /\
       /\/  \
      /      \  /\      ...
              \/
    

    All we need to do is to find the lowest point as our starting line.

    Here's my solution with one pass and O(1) space.

    public class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            int sum = 0, minGas = 0, index = 0;
            for (int i=0; i<gas.length; ++i) {
                sum += gas[i]-cost[i];
                if (sum<minGas) {
                    minGas = sum;
                    index = i+1;
                }
            }
            return sum>=0?(index==gas.length?0:index):-1;
        }
    }
    

Log in to reply
 

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