There are N gas stations along a circular route, where the amount of gas at station i is gas[i]
.
You have a car with an unlimited gas tank and it costscost[i]
of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Given 4
gas stations with gas[i]=[1,1,3,1]
, and thecost[i]=[2,2,1,1]
. The starting gas station's index is 2
.
public class Solution { /** * @param gas: an array of integers * @param cost: an array of integers * @return: an integer */ public int canCompleteCircuit(int[] gas, int[] cost) { // write your code here if(gas == null || gas.length == 0 || cost == null || cost.length == 0 || gas.length != cost.length) return -1; int gas_sum = 0; int cost_sum = 0; for(int i = 0; i < gas.length; i++) gas_sum += gas[i]; for(int i = 0; i < cost.length; i++) cost_sum += cost[i]; if(gas_sum < cost_sum) return -1; int left = 0; int start = 0; while(start < gas.length){ int i = start; for(; i < gas.length; i++){ left += gas[i]; left -= cost[i]; if(left < 0){ left = 0; break; } } if(i != gas.length) start = i + 1; else return start; } return -1; }}