-
Notifications
You must be signed in to change notification settings - Fork 1
/
134. Gas Station.cpp
44 lines (43 loc) · 1.14 KB
/
134. 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
44
// TC - O(N^2)
// SC - O(1)
/***************************************************************
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
for(int i = 0; i < n; i++) {
int gasRem = gas[i] - cost[i];
int itr = (i+1)%n;
while(gasRem >= 0 && itr != i) {
gasRem += gas[itr];
gasRem -= cost[itr];
if(gasRem < 0) break;
itr = (itr+1)%n;
}
if(itr == i && gasRem >= 0) return itr;
}
return -1;
}
};
*************************************************************/
// TC - O(N)
// SC - O(1)
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int start = gas.size()-1;
int end = 0;
int sum = gas[start] - cost[start];
while(start > end) {
if (sum >= 0) {
sum += gas[end] - cost[end];
++end;
}
else {
--start;
sum += gas[start] - cost[start];
}
}
return sum >= 0 ? start : -1;
}
};