思路
很清晰的可以看到,首先start加油站的left一定要大于0,然后从start开始一直到start-1,currentGas 一定要大于等于0
首先找到合适的start
如果a->b此时currentGas小于0了,则新的start一定从b+1往后找,而不用从a+1往后找。
如果新的start是c,c在a-b之间,首先a-c是大于等于0的,c到b加上a-c的剩余汽油值一定是大于等于c到b的,但是a到b小于0,所以c到b也一定小于0
有点抽象
代码
public int canCompleteCircuit(int[] gas, int[] cost) {
int[] left = new int[gas.length];
int sum = 0;
for (int i = 0; i < gas.length; i++) {
left[i] = gas[i] - cost[i];
sum = sum + left[i];
}
if (sum < 0){
return -1;
}
int index = 0;
int start = 0;
int currentLeftGas = 0;
while (index < gas.length){
if (left[index] >= 0){
start = index;
while (index <gas.length){
currentLeftGas = currentLeftGas + left[index];
if (currentLeftGas < 0){
currentLeftGas = 0;
start = -1;
break;
}
index++;
}
}
index++;
}
if (start == -1){
return -1;
}
for (int i = 0 ;i < start; i++){
if(currentLeftGas + left[i] >=0){
currentLeftGas = currentLeftGas + left[i];
}
else {
return -1;
}
}
return start;
}