problem
solution
- brute force , TLE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
int n = gas.size();
for(int i=0;i<n ; ++i){
// i 為起點
int cur = 0;
for(int j = 0;j<n ; j++){
cur+=(gas[(i+j)%n] - cost[(i+j)%n] );
if(cur<0) break;
}
if(cur>=0) return i;
}
return -1;
}
};
option 1 - greedy
1 | class Solution { |
analysis
- time complexity
O(n)
- space complecity
O(1)