这道题和剑指offer那个求最大和的题目有点类似,当之前的和为负的时候就可以舍弃,还有个小陷阱,全程的油量必须大于耗油,这是个圆圈跑道。
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int shengyu=0;
int begin=0;
int total=0;
int remainning=0;
for(int i=0;i<gas.length;i++){
shengyu+=gas[i];
shengyu-=cost[i];
remainning = gas[i]-cost[i];
total += remainning;
if(shengyu<0){
begin = i+1;
shengyu=0;
continue;
}else{
continue;
}
}
if(total>=0){
return begin;
}else{
return -1;
}
}
}