Gas Station
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.
一开始显然想到暴力破解
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int pgas, pcost, i, j, k;
vector<int> passcost;
for(i = 0; i < gas.size(); i++){
passcost.push_back( gas[i] - cost[i]);
}
for(j = 0; j < gas.size(); j++){
if(passcost[j] < 0) continue;
pgas = passcost[j];
for(k = 0; k< gas.size(); k++){
pgas += passcost[((j+k)%gas.size())];
if(pgas < 0) break;
}
if(k == gas.size()) return j;
}
return -1;
}
};
果然 time limited exceed
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int pgas, pcost, i, j, k;
vector<int> passcost;
int sum = 0;
for(i = 0; i < gas.size(); i++){
passcost.push_back( gas[i] - cost[i]);
sum += gas[i] - cost[i];
}
if(sum < 0) return -1;
int stMax=0, stmax=0, endMin=0;
int min = passcost[0], MIN = 0, max = passcost[0], MAX= 0;
for( i = 1; i < gas.size(); i++){
if(max < 0){
max = passcost[i];
stmax = i;
}
else max+=passcost[i];
if(max > MAX){
MAX = max;
stMax = stmax;
}
if(min > 0){
min = passcost[i];
}
else min += passcost[i];
if(min < MIN)
{
MIN = min;
endMin = i;
}
}
return (MAX >= (sum - MIN) ? stMax : (endMin+1) % gas.size());
}
};
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int sum = 0, tem = 0, total = 0, i;
for(i = 0; i < gas.size(); i++){
total += gas[i] - cost[i];
if(sum >= 0){
sum += gas[i] - cost[i];
}
else{
sum = gas[i] - cost[i];
tem = i;
}
}
if(total < 0) return -1;
else return tem;
}
};