Skip to content

Commit ed95390

Browse files
committed
Gas station
1 parent 6bafc82 commit ed95390

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Queue/GasStation.cpp

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#include <iostream>
2+
#include <vector>
3+
using namespace std;
4+
5+
int canCompleteCircuit(vector<int> &gas, vector<int> &cost)
6+
{
7+
int totGas = 0, totCost = 0;
8+
9+
// unique solution
10+
int start = 0, currGas = 0;
11+
12+
for (int i = 0; i < gas.size(); i++)
13+
{
14+
totGas += gas[i];
15+
totCost += cost[i];
16+
currGas += (gas[i] - cost[i]);
17+
18+
if (currGas < 0)
19+
{
20+
start = i + 1;
21+
currGas = 0;
22+
}
23+
}
24+
25+
return totGas < totCost ? -1 : start;
26+
}
27+
28+
int main()
29+
{
30+
vector<int> gas = {1, 2, 3, 4, 5};
31+
vector<int> cost = {3, 4, 5, 1, 2};
32+
33+
cout << canCompleteCircuit(gas, cost) << endl;
34+
35+
return 0;
36+
}

Queue/GasStation.exe

58.9 KB
Binary file not shown.

0 commit comments

Comments
 (0)