BiruLyu
8/3/2017 - 8:46 PM

134. Gas Station(#).java

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {

       int start = gas.size()-1;
       int end = 0;
       int sum = gas[start] - cost[start];
       while (start > end) {
          if (sum >= 0) {
             sum += gas[end] - cost[end];
             ++end;
          }
          else {
             --start;
             sum += gas[start] - cost[start];
          }
       }
       return sum >= 0 ? start : -1;
    }
};
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = 0, total = 0, tank = 0;
        for (int i = 0; i < gas.length; i++) {
            if ((tank = tank + gas[i] - cost[i]) < 0) {
                start = i + 1;
                total += tank;
                tank = 0;
            }
        }
        return total + tank < 0 ? -1 : start;
    }
}
/*
[4]
[5]
[1,2,3,4,5]
[2,5,1,2,1]
[1,2]
[2,1]
*/
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if  (gas == null || cost == null || gas.length < 1 || cost.length < 1) return -1;
        int len = gas.length;
        int[] left = new int[len];
        int sum = 0;
        for (int i = 0; i < len; i++) {
            left[i] = gas[i] - cost[i];
            sum += left[i];
        }
        if (sum < 0) return -1;
        int curLeft = 0;
        int res = 0;
        for (int i = 0; i < len; i++) {
            curLeft += left[i];
            if (curLeft < 0) {
                res = i + 1;
                curLeft = 0;
            } 
        }
        return res;
    }
}