-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGas Station.cpp
More file actions
32 lines (32 loc) · 963 Bytes
/
Gas Station.cpp
File metadata and controls
32 lines (32 loc) · 963 Bytes
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
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<int> diff;
int size = gas.size();
if(size == 0)
return -1;
for(int i = 0; i < size; ++i)
diff.push_back(gas[i] - cost[i]);
for(int i = 0; i < size; ++i)
diff.push_back(diff[i]);
int left = 0, right = 0;
int sum = 0;
while(left < size)
{
while(right < 2 * size && sum >= 0)
{
if(right - left == size)
return left;
sum += diff[right];
++right;
}
while(left < size && left < right && sum < 0)
{
sum -= diff[left];
++left;
}
}
return -1;
}
};