There was N gas stations along a circular route, where the amount of gas at Station I 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 its 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.
Ideas:
1. Can I travel around? = as long as gas[] plus total and-cost[] plus Total and > 0, will be able to. = = requires an int to calculate the sum of gas[]-cost[]
2. How do I find the starting point? If the oil is not enough at a certain station, then the starting point must be re-searched from behind it. = = requires an int to record the amount of oil from the starting point found so far
Time complexity O (n)
classSolution { Public: intCancompletecircuit (vector<int> &gas, vector<int> &Cost ) { intsum =0, total =0, Len = Gas.size (), index =-1; for(intI=0; i<len; i++) {sum+ = gas[i]-Cost[i]; Total+ = gas[i]-Cost[i]; if(Sum <0) {Index=i; Sum=0; } } returntotal>=0? index+1: -1; }};
134 gas station (Array; DP)