https://oj.leetcode.com/problems/gas-station/
Calculate the refueling difference for each petrol station diff[]. Gets an array. From the greedy point of view, if we find a maximum substring, then starting from his starting L, can go straight ahead and accumulate the largest amount of petrol.
One conjecture is: If the petrol is not enough to go through the whole process, then no matter where you can go through the whole process.
Can disprove: If starting from P can go through the whole process. Then the molecular string from P to L will be greater than 0, and this molecule string plus l start maximal substring can make the substring larger. Then with the maximum substring starting from l the contradiction. So there's no such p.
Therefore, using the maximum substring algorithm to find the maximum substring of the beginning L, and then perform a simulation, you can determine whether to complete the whole process.
classSolution { Public: intn,m; intCancompletecircuit (vector<int> &gas, vector<int> &Cost ) {N=gas.size (); Vector<int> d=Gas ; for(intI=0; i<n;i++) d[i]-=Cost[i]; intl=-1; intmaxs=-1; intcs=-1; intcl=-1; for(intI=0;i<2*n;i++) { intci=i%N; if(cs<0) {cs=d[ci];cl=CI;} Elsecs+=D[ci]; if(cs>maxs) {Maxs=CS; L=cl; } } intCur=0; for(intI=0; i<n;i++) { intcp= (l+i)%N; Cur+=D[CP]; if(cur<0)return-1; } returnl; }};
Leetcode-gas station-gas station-Maximum SUBSTRING algorithm application