Here is a summary of the problem:
You are to implement a class called Solution, which has a public method:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost); |
The two vectors are the same size, and they contain non-negative integers. They represent gas stations. You will start at a station s, with an empty tank of gas in your car. You will add gas[s] gallons of gas to your car, and then it will take cost[s] gallons of gas to get to the next station (station (s+1)%gas.size()). Your car holds an infinite amount of gas.
You should return the index of s, which is your starting station, if it is possible to visit every station, and return to s, without running out of gas. If there is no such station, return -1. The problems are such that if s exists, it is unique.
Example | Gas | Cost | Answer |
1 | { 1, 2, 3, 4, 5 } |
{ 3, 4, 5, 1, 2 } |
3 |
2 | { 2, 3, 4 } |
{ 3, 4, 3 } |
-1 |
Then, you can call starting_with_i() with every value of i, and answer the problem. I hope that you see that such a solution is O(n2), so it's unacceptable as n grows. And leetcode will give you large problems to make such a solution fail.
So, you can't test every starting position. However, suppose you call starting_with_i(0), and graph the amount of gas you have at every station, regardless of whether that amount goes negative. Do that by hand for example 1 above. Do you see how doing that gives you an O(n) solution to the problem?
If Leetcode's servers are working, go ahead and solve it there. Otherwise, you can test yourself with test.sh, and your output should be identical to answers.txt. Each test should take under a second, even that last one which has 510,000 stations!