Definitely not the best solution... Just some thoughts help myself to understand.
Let's define** P(i,j) as the probability that the train can leave station i for station j before run out of gas. In this problem, we know P should either be 1 (can arrive) or 0 (cannot arrive). Now the probability that we start from station 0, through N stations finally arrive station N is presented by P(0,N).
Now let station k be the station between station 0 and station N (0
Now in this problem, assume there must be one achievable train routine, our choice is actually very limited. So by rejecting the enough choices, we could quickly find the answer.
Like the illustration above, we could simplify this problem as moving a rectangle of size N+1 with its starting point limited in area 0 to N. We calculate the sum from left to right, as long as the sum goes from positive to negative, for example, sum from 0 to z is positive, but from 0 to z+1 is negative, we could say P(0,z) suddenly goes to negative when becomes P(0,z+1). Since we have already proved that P(0,N)=P(0,k)P(k,N)*, so the only possibility causing the change from P(0,z)=1 to P(0,z+1)=0 is P(z,z+1)=0.So as we proved we could reject all the points from 0 to Z as starting points. Then we choose point z+1 as the new starting points and repeat the above process. Notice since the rectangle has size N+1, so we only need to check the sum of at most N+1 points.
Finally the first point we are unable to reject and is within first N+1 points is the answer. Otherwise, there is no such situation that train can travel all through. The complexity is O(n). ( n = number of the station).
class Solution {
public:
int canCompleteCircuit(vector& gas, vector& cost) {
int count=0;
int sum=0;
int start=0;
int target_size=gas.size();
for(int i=0;i