題目如下:
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.hild.
我的提交:
/*17.3.31
*有點像最大連續(xù)子序列和的動態(tài)規(guī)劃解法
*如果total大于0影斑,從左到右掃描,一定能切分出一個和大于0的區(qū)間(起點為i,終點為數(shù)組的結(jié)尾)
*如-1控淡,-2慎式,2赛惩,3,-6,10
*-1被切開散休,-2被切開次屠,3园匹,4,-6被切開劫灶,10大于0裸违,所以以10為起點!
*換一個順序-6浑此,10累颂,-1,-2凛俱,2紊馏,3
*-6被切開,10~3大于0蒲犬,結(jié)果還是以10為起點朱监。
*/
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = 0,total = 0;
for(int i=0,tank=0;i<gas.length;i++){
if(tank<0){
tank = gas[i] - cost[i];
start = i;
}
else{
tank += gas[i] - cost[i];
}
total += gas[i] - cost[i];
}
return total<0?-1:start;
}
}