## C++ algorithm learning (Likou: 134. Gas station)

There are N gas stations on a ring road, and the i-th gas station has gasoline gas[i] liters.

You have a car with an unlimited fuel tank. Driving from the i-th gas station to the i+1-th gas station requires cost[i] liters of gasoline. You start from one of the gas stations and the gas tank is empty at the beginning.

If you can go around the loop, return the number of the gas station when you started, otherwise return -1.

Description:

If the question has a solution, that answer is the only answer.
The input arrays are all non-empty arrays and have the same length.
The elements in the input array are all non-negative numbers.
Example 1:

``````输入:
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

``````

Example 2:

``````输入:
gas  = [2,3,4]
cost = [3,4,3]

``````

Source: LeetCode (LeetCode)
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Personal problem solution: The purpose of this problem is to find whether the oil is enough to the end, then we need to judge two points: 1. The total oil can run all the way, this is a solution. 2. If there is a solution, start looking for the first solution.

``````class Solution {

public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {

int gas_min_cost = 0;//总油数量
int start = 0; //起始位置
int num = 0;  //每次的数
for(int i = 0;i < gas.size();i++){

num += (gas[i] - cost[i]);
gas_min_cost +=(gas[i] - cost[i]);
if(num < 0){

start = i+1;
num = 0;
}
}
if(gas_min_cost <0 ) return -1;
return start;
}
};
``````

### Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/109779868
Recommended
Ranking
Daily