@@ -42,3 +42,54 @@ Therefore, you can't travel around the circuit once no matter where you start.
4242
4343- Array
4444- Greedy
45+
46+ ## Solution
47+
48+ If there is more gas along the route than the cost of the route, then there is guaranteed to be a solution to the problem.
49+ So the first step is to check if the sum of the gas is greater than or equal to the sum of the cost. If it is not, then
50+ we return -1.
51+
52+ Next, we iterate through the gas station to find the starting index of our circuit using a greedy approach: whenever we
53+ don't have enough gas to reach the next station, we move our starting gas station to the next station and reset our gas
54+ tank.
55+
56+ We start at the first station, and fill our tank with gas[ 0] = 5 units of gas. From there, it takes cost[ 0] = 1 units of
57+ gas to travel to the next station, so we arrive at station 2 (index 1) with 4 units of gas.
58+
59+ ![ Solution 1] ( ./images/solutions/gas_stations_solution_1.png )
60+ ![ Solution 2] ( ./images/solutions/gas_stations_solution_2.png )
61+ ![ Solution 3] ( ./images/solutions/gas_stations_solution_3.png )
62+
63+ At station 2, we fill our tank with gas[ 1] = 2 units of gas, for a total of 6 units of gas. It takes cost[ 1] = 5 units
64+ of gas to travel to the next station, so we arrive at station 3 with 1 unit of gas
65+
66+ ![ Solution 4] ( ./images/solutions/gas_stations_solution_4.png )
67+ ![ Solution 5] ( ./images/solutions/gas_stations_solution_5.png )
68+
69+ Now at station 3, we fill our tank with gas[ 2] = 0 units of gas, for a total of 1 unit of gas. It takes cost[ 2] = 5 units
70+ of gas to travel to the next station, which we don't have.
71+
72+ This is where our greedy approach comes in. We reset our starting station to the next station i + 1 and reset our gas
73+ tank to 0. We can do this because all other start indexes between 0 and 2 will also run into the same problem of not
74+ having enough gas to reach the next station, so we can rule them out.
75+
76+ ![ Solution 6] ( ./images/solutions/gas_stations_solution_6.png )
77+ ![ Solution 7] ( ./images/solutions/gas_stations_solution_7.png )
78+
79+ If we follow this approach of resetting the start index and gas tank whenever we don't have enough gas to reach the next
80+ station, then when we finish iterating, the last start index will be the solution to the problem.
81+
82+ ![ Solution 8] ( ./images/solutions/gas_stations_solution_8.png )
83+ ![ Solution 9] ( ./images/solutions/gas_stations_solution_9.png )
84+ ![ Solution 10] ( ./images/solutions/gas_stations_solution_10.png )
85+ ![ Solution 11] ( ./images/solutions/gas_stations_solution_11.png )
86+
87+ ### Complexity Analysis
88+
89+ #### Time Complexity
90+
91+ O(n) where n is the number of gas stations. We only iterate through the gas stations once.
92+
93+ #### Space Complexity
94+
95+ O(1) We only use constant extra space for variables.
0 commit comments