1 /*
 2  * @Author: yaodaoteng
 3  * @Date: 2020-12-03 16:56:18
 4  * @LastEditors: yaodaoteng
 5  * @LastEditTime: 2020-12-03 17:16:50
 6  * @FilePath: \leetcode\134.加油站.cpp
 7  */
 8 /*
 9  * @lc app=leetcode.cn id=134 lang=cpp
10  *
11  * [134] 加油站
12  */
13 
14 // @lc code=start
15 class Solution {
16 public:
17 /*每个加油站的剩余量remain[i]为gas[i] - cost[i]。
18 
19 i从0开始累加remain[i],和记为curSum,如果curSum小于零,说明 [0, i]区间都不能作为起始位置,起始位置从i+1算起。
20 
21 */
22     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
23         int cursum = 0;
24         int totalsum = 0;
25         int start = 0;
26         for(int i = 0; i < gas.size();i++){
27             cursum += gas[i] - cost[i];
28             totalsum += gas[i] - cost[i];
29             if(cursum<0){
30                 start = i + 1;
31                 cursum = 0;
32             }
33         }
34         if(totalsum<0)
35             return -1;
36         return start;
37     }
38 };
39 // @lc code=end