134. 加油站https://leetcode-cn.com/problems/gas-station/
⾸先如果总油量减去总消耗⼤于等于零那么⼀定可以跑完⼀圈,说明各个站点的加油站剩油量rest[i]相加⼀定是⼤于等于零的。
每个加油站的剩余量rest[i]
为
gas[i] - cost[i]
。
i从
0
开始累加
rest[i]
,和记为
curSum
,⼀旦
curSum
⼩于零,说明
[0, i]
区间都不能作为起始位置,起始位置从
i+1
算起,再从0
计算
curSum
。
那么为什么⼀旦[i
,
j]
区间和为负数,起始位置就可以是
j+1
呢,
j+1
后⾯就不会出现更⼤的负数?
如果出现更⼤的负数,就是更新j
,那么起始位置⼜变成新的
j+1
了。
⽽且j
之前出现了多少负数,
j
后⾯就会出现多少正数,因为耗油总和是⼤于零的(前提我们已经确定了⼀定可以跑完全程)。
那么局部最优:当前累加rest[j]
的和
curSum
⼀旦⼩于
0
,起始位置⾄少要是
j+1
,因为从
j
开始⼀定不⾏。全局最优:找到可以跑⼀圈的起始位置。
public int canCompleteCircuit(int[] gas, int[] cost) {
int result = 0, current = 0, total = 0;
for (int i = 0; i < gas.length; i++) {
current += gas[i] - cost[i];
total += gas[i] - cost[i];
if (current < 0){
current = 0;
result = i + 1;
}
}
if (total < 0){
return -1;
}
return result;
}