-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path134_Gas_Station.cc
42 lines (41 loc) · 1.06 KB
/
134_Gas_Station.cc
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
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
if(gas.size()==0||cost.size()==0||gas.size()!=cost.size()) return -1;
vector<int> nums(gas.size(),0);
for(int i=0;i<gas.size();++i){
nums[i]=gas[i]-cost[i];
}
int n=nums.size();
int max=0,start=0;
int prev=0,cur=0,sum=0;
for(int i=0;i<n;++i){
if(sum+nums[i]<=nums[i]){
if(sum>max){
sum=max;
start=prev;
}
prev=i;
sum=nums[i];
}
else{
sum+=nums[i];
}
}
for(int i=0;i<n;++i){
if(sum+nums[i]>sum) sum+=nums[i];
else break;
}
if(sum>max){
sum=max;
start=prev;
}
sum=0;
for(int i=start;i<n+start;++i){
if(i>=n) sum+=nums[i-n];
else sum+=nums[i];
if(sum<0) return -1;
}
return start;
}
};