-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 543 ms (5.17%), Space: 69.5 MB (56.01%) - LeetHub
- Loading branch information
1 parent
0a99c17
commit 7fd9a94
Showing
1 changed file
with
30 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,24 +1,40 @@ | ||
class Solution { | ||
public: | ||
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { | ||
|
||
int n=gas.size(); | ||
int total_gas=0,total_cost=0; | ||
int curr_gas=0, starting_point=0; | ||
for(int i=0;i<n;i++) | ||
int ans=0; | ||
int amt=0; | ||
int fnt=0; | ||
int cnt=0; | ||
if(n==1) | ||
{ | ||
//these two variable are to check if no case is possible | ||
total_gas+=gas[i]; | ||
total_cost+=cost[i]; | ||
//for checking the total present gas at index i | ||
curr_gas+=gas[i]-cost[i]; | ||
if(curr_gas<0) | ||
if(gas[0]-cost[0]>=0)return 0; | ||
else return -1; | ||
} | ||
for(int i=0;i<n;i=(i+1)%n) | ||
{ | ||
if(cnt==2*n)break; | ||
if(fnt==0)ans=i; | ||
cout<<i<<" "; | ||
if(i==ans && fnt==1)return i; | ||
|
||
if(amt+gas[i]>=cost[i]) | ||
{ | ||
amt+=gas[i]; | ||
amt-=cost[i]; | ||
} | ||
else if(amt+gas[i]<cost[i]) | ||
{ | ||
//there is a breakdown....so we will start from next point or index | ||
starting_point=i+1; | ||
//reset our fuel | ||
curr_gas=0; | ||
amt=0; | ||
ans=(i+1)%n; | ||
fnt=0; | ||
} | ||
|
||
if(i==ans)fnt=1; | ||
cnt++; | ||
} | ||
return (total_gas<total_cost)?-1:starting_point; | ||
return -1; | ||
|
||
} | ||
}; |