Problem Description:
There was N gas stations along a circular route, where the amount of gas at StationI was gas[i] .
You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i] I to their next station ( I+ 1). You begin the journey with a 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.
Code:
int Cancompletecircuit (vector<int> &gas, vector<int> &cost) {//c++ if (gas.size () ==0| | cost.si Ze () ==0| | Gas.size ()!=cost.size ()) return-1; int size = Gas.size (); Vector<int> left (size); for (int i=0; i<size; i++) left[i]=gas[i]-cost[i]; int max=left[0],begin=0,temp=0,index=begin; for (int i=0; i<size; i++) {temp + = Left[i]; if (Temp > max) {max = temp; index = BEGIN; } if (Temp < 0) {temp = 0; begin = I+1; }} if (temp >=0 && begin!=0) {for (int i=0; i<size; i++) {temp + = Le Ft[i]; if (Temp > Max) {max =temp; index = BEGIN; } if (temp <0) break; }} temp = 0; for (int i= 0; i<size; i++) {temp +=left[(i+index)%size]; if (temp <0) return-1; } return index; }
[Leetcode] Gas station