Because the total gas is greater than the total cost of time. You will be able to circle the whole city.
First Solution :
If there is enough oil at the beginning. Departure from position I. The remaining amount of oil at position K is L (i,k).
to the random K. L (i,k) According to the difference of I, only the difference constant.
We just need to find the smallest L (0, K) corresponding to the k,k+1 to be asked.
The code is as follows:
int Cancompletecircuit (vector<int> &gas, vector<int> &cost) { int start = 0; int Curgas = 0, Mingas = 0, Totalgas = 0; for (int i = 0; i < gas.size (); i++) { int temp = gas[i]-cost[i]; Curgas + = temp; Totalgas + = temp; if (Mingas > Curgas) { start = i + 1; Mingas = Curgas; } } if (totalgas >= 0) return start% gas.size (); else return-1; }
Another solution:
Assuming L (I,k) < 0, the entire position between I and K is not to K
So from the location of the k+1 from 0 to start looking for
int Cancompletecircuit (vector<int> &gas, vector<int> &cost) { int start = 0; int Curgas = 0, Totalgas = 0; for (int i = 0; i < gas.size (); i++) { int temp = gas[i]-cost[i]; Curgas + = temp; Totalgas + = temp; if (Curgas < 0) { start = i + 1; Curgas = 0; } } if (totalgas >= 0) return start% gas.size (); else return-1; }
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Gas station [Leetcode] two solutions