Poison

134. Gas Station

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int totalRemainingGas = 0, remainingGas = 0, startIndex = 0;
for (int i = 0; i < gas.length; i++) {
totalRemainingGas += gas[i] - cost[i];
remainingGas += gas[i] - cost[i];
if (remainingGas < 0) {
// 无法到达下一个加油站,只能从下一个加油站开始枚举
remainingGas = 0;
startIndex = (i + 1) % gas.length;
}
}

return totalRemainingGas < 0 ? -1 : startIndex;
}
}
Reference

134. Gas Station
Java 1ms 详细说明起始点选取过程