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.
Note:
The solution is guaranteed to be unique.
加油站问题,有n个加油站,在一个环形上,从一个加油站到另一个加油站需要cost[i]的油量,加油站中有gas[i]的油量,问是否能够从一个加油站出发,绕一圈,可以的话返回出发的加油站,不可以的话返回-1
我们来证明:若油站的总油量大于等于路途的总消耗,那么一定可以走完一圈。
从加油站i 经过加油站j 到达加油站k等价于将j的油量全部放到i,然后从i走到k,如此等价,可以证明走一圈其实就等价于所有油量减去所有消耗
如何找这个出发点?假设车子开始有无限多的油,从任意一个加油站出发,走一圈,记录在每一个加油站的剩余油量,剩余油量最小的加油站,就是要出发的加油站。
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int totalGas = 0;
int totalCost = 0;
for(int i = 0; i < gas.size(); i++) {
totalGas += gas[i];
}
for(int i = 0; i < cost.size(); i++) {
totalCost += cost[i];
}
if(totalGas < totalCost) return -1;
int minPos = 0;
int startGas = INT_MAX - (totalGas);
int index = 0;
int minRemain = INT_MAX;
while(index < gas.size()) {
if(startGas < minRemain) {
minPos = index;
minRemain = startGas;
}
startGas = startGas + gas[index] - cost[index];
index++;
}
return minPos;
}
};