-
Notifications
You must be signed in to change notification settings - Fork 16
/
gas-station.cpp
43 lines (35 loc) · 916 Bytes
/
gas-station.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int size = gas.size();
int cur = 0;
int start = 0;
int end = 0;
do
{
while (cur >= 0)
{
cur += (gas[end]-cost[end]);
end = (end+1)%size;
if (end == start)
{
break;
}
}
while (cur < 0)
{
start = (start+size-1)%size;
cur += gas[start] - cost[start];
if (end == start)
{
break;
}
}
}while (start != end);
if (cur >= 0)
{
return start;
}
return -1;
}
};