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 costs cost[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.
Note:
The solution is guaranteed to be unique.
思路:这道题目和求最大连续子数组的和很类似。遍历一遍数组,记录下 total=total+gas[i]-cost[i]; 其中total表示的是走完一遍所有的加油站,还剩下的油量,如果total小于0,说明要走完所有的加油站是不可能的,否则走完所有的加油站是可能的。 用sum记油录下连续子数组的和,
- 如果sum小于0,说明从start走到当前的i站点是不可能的,因为油不够,那么车主应该选择从下一个站点尝试,并记录下一个站点,即start
- 如果sum大于0,则继续往后走
最后,判断total,如果total小于0,即返回-1,表示不能走完所有的站点,如果total大于0,返回当前连续子数组的起始位置start。
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n=gas.length;
if(n==0) return -1;
int sum=0;
int total=0;
int start=0;
for(int i=0;i<n;i++)
{
total=total+gas[i]-cost[i];
if(sum<0)
{
sum=gas[i]-cost[i];
start=i;
}else{
sum+=gas[i]-cost[i];
}
}
if(total<0) return -1;
else return start;
}
}