[Leetcode] 134 Gas Station (Classic dp | greedy)
(1) The most common solution is the O (n2) solution.
Pre-process the array of gas [I]-cost [I] and start from each non-negative position. As long as a loop can be completed, the result can be output;
After thinking and inference, we can conclude that for a loop array, if the overall array and SUM> = 0, then, we can find such an element in the array: Starting from this array element, this element is circled around the array, which ensures that the sum is always out of the non-negative state.
Therefore, you only need to compare the values of sum and 0 to determine whether there is a solution.
(2) continue to abstract the problem. We certainly hope that the first journey will be "Fuel"> "consumption". In this way, we can accumulate the amount of fuel to cope with the subsequent large consumption. Based on this idea, convert it into the sum of the largest continuous subsequences of the array (and record the starting subscript). This is a problem we have previously encountered, such as hdu 1003;
But because it is a loop array, we have to consider a situation: the first and last are all positive numbers. What should we do? We only need to record and obtain the sum of the smallest consecutive subsequences, and finally obtain the maximum values of Maxsum and sum-Minsum. In addition, the Minsum sub-mark must be added with an remainder to return.
Class Solution {public: int canCompleteCircuit (vector
& Gas, vector
& Cost) {int sum = 0; for (int I = 0; I
Maxsum) {Maxsum = tot1; Maxpos = CurMaxp;} if (tot2 + gas [I]> gas [I]) // minimum continuous subsequence and tot2 = gas [I]; else tot2 + = gas [I]; if (tot2
= (Sum-Minsum) return Maxpos; else return (Minpos + 1) % gas. size ();}};
(3) There is another simple idea. First, we start from site I. If we reach the current site cur and our fuel volume is less than 0, we only need to start testing from cur + 1. I will not prove it here, but we can think about it from a macro perspective. The oil volume of any prefix site segment must be greater than 0, so remove any prefix, this will only reduce the amount of fuel, so we can only try again from cur + 1.
class Solution {public: int canCompleteCircuit(vector
& gas, vector
& cost) { int sum=0; for(int i=0;i