Skip to content

Commit 9a3aa47

Browse files
solved on 13/12/2023
1 parent cf667ba commit 9a3aa47

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

LC_101_GasStation.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// tc : O(n) sc : O(1)
5+
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
6+
{
7+
int deficit = 0; // deficit is the amount of gas we need to reach the next station
8+
int balance = 0; // balance is the amount of gas we have in our tank which is calculated by subtracting the cost from the gas
9+
// index of the starting point
10+
int start = 0;
11+
12+
for (int i = 0; i < gas.size(); i++)
13+
{
14+
int temp = balance + gas[i] - cost[i]; // balance after reaching the next station from the current station, if negative we can't reach the next station
15+
if (temp < 0)
16+
{
17+
// if balance is negative, we can't start from this station
18+
// as we will run out of gas before reaching the next station
19+
// so we start from the next station
20+
start = i + 1;
21+
// deficit is the amount of gas we need to reach the next station
22+
deficit += abs(temp);
23+
// reset balance
24+
balance = 0;
25+
}
26+
else
27+
{
28+
balance = temp;
29+
}
30+
}
31+
// if the total balance is less than the total deficit, we can't complete the circuit
32+
// else we can start from the start index
33+
return (balance - deficit >= 0) ? start : -1;
34+
}
35+
36+
int main()
37+
{
38+
vector<int> gas = {1, 2, 3, 4, 5};
39+
vector<int> cost = {3, 4, 5, 1, 2};
40+
cout << canCompleteCircuit(gas, cost) << endl;
41+
return 0;
42+
}

0 commit comments

Comments
 (0)