Skip to content

Commit

Permalink
Time: 543 ms (5.17%), Space: 69.5 MB (56.01%) - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
Dipendra-Raghav committed Jan 8, 2023
1 parent 0a99c17 commit 7fd9a94
Showing 1 changed file with 30 additions and 14 deletions.
44 changes: 30 additions & 14 deletions 0134-gas-station/0134-gas-station.cpp
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;

}
};

0 comments on commit 7fd9a94

Please sign in to comment.