LeetCode 134 Gas Station

其实就是找到序列中最大和序列,数量为gas[i] - cost[i],寻找的方法一样,然后就是从先走这个最大序列和的序列,然后再走之前和为负的序列。要计算和为负的累计。

C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int ans = 0, left = 0, accumulate = 0;
for(int i = 0; i < gas.size(); i++){
left += gas[i] - cost[i];
if(left < 0){
ans = i+1;
accumulate += left;
left = 0;
}
}
if(left + accumulate >= 0){
return ans;
}else{
return -1;
}
}
};