There are N petrol stations on a ring road, of which petrol gas[i]
is raised at the first petrol station.
You have a car with an unlimited fuel tank, from the I gas station to cost[i]
The first i+1 gas station. You start off with one of the gas stations and the fuel tank is empty at the beginning.
If you can travel around the loop for a week, return the gas station number at the time of departure, otherwise return-1.
Description
- If the topic has a solution, the answer is the only answer.
- Input arrays are non-empty arrays and are of the same length.
- The elements in the input array are non-negative.
Example 1:
Input: Gas = [1,2,3,4,5]cost = [3,4,5,1,2] Output: 3 explanation: 4 litres of petrol can be obtained from a petrol station at 3rd (index 3). At this time the fuel tank has = 0 + 4 = 4 liters of petrol to the 4th gas station, at this time the tank has 4-1 + 5 = 8 liters of petrol to the No. 0 gas station, when the tank has 8-2 + 1 = 7 liters of petrol to the 1th gas station, when the tank has 7-3 + 2 = 6 liters of petrol bound Gas station 2nd, at this time the tank has 6-4 + 3 = 5 liters of petrol to the 3rd gas station, you need to consume 5 liters of petrol, just enough to return to the station No. 3rd. Therefore, 3 can be the starting index.
Example 2:
Input: gas = [2,3,4]cost = [3,4,3] Output:-1 Explanation: You cannot start at station NO. 0 or 1th because there is not enough petrol to allow you to travel to the next gas station. We can get 4 litres of petrol from gas station No. 2nd. At this time the fuel tank has = 0 + 4 = 4 liters of petrol to the No. 0 gas station, at this time the tank has 4-3 + 2 = 3 liters of petrol to the 1th gas station, the tank has 3-3 + 3 = 3 liters of petrol you can not return to the station 2nd, because the return needs to consume 4 liters of petrol, but your tank only There are 3 litres of petrol. So, no matter what, you can't travel around the loop for a week.
- If the starting index can be found, then there must be sum (gas) >= sum (cost), which is necessary.
- Traversing from the beginning, if you have sum (gas) < sum (cost) to an index (recorded as x), you cannot get an answer from X. Correspondingly, x+1 ... it is impossible to get an answer until the current index. Because it is cumulative, the next traversal should start at x + 1. This answer is somewhat similar to maximal subarray.
classSolution { Public: intCancompletecircuit (vector<int>& Gas, vector<int>&Cost ) { intTotal =0, sum =0, start =0; for(inti =0; I < gas.size (); i++) { Total+ = Gas[i]-Cost[i]; Sum+ = Gas[i]-Cost[i]; if(Sum <0) {Start= i +1; Sum=0; } } returnTotal <0? -1: Start; }};
Leetcode 134. Gas station