Skip to content

Commit 3d3c010

Browse files
committed
feat: add explanation
1 parent 28e3603 commit 3d3c010

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

leetcode/gas_station/solution.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,26 @@
11
class Solution:
2+
"""
3+
Gas Station Circuit - Greedy Approach
4+
5+
Visual Example: gas=[1,2,3,4,5], cost=[3,4,5,1,2]
6+
7+
Station: 0 1 2 3 4
8+
┌─┐ ┌─┐ ┌─┐ ┌─┐ ┌─┐
9+
Gas: │1│ │2│ │3│ │4│ │5│
10+
└─┘ └─┘ └─┘ └─┘ └─┘
11+
Cost: 3 4 5 1 2
12+
↓ ↓ ↓ ↓ ↓
13+
Net: -2 -2 -2 +3 +3
14+
15+
Algorithm trace:
16+
i=0: tank=0+(-2)=-2 < 0 → reset tank=0, start=1
17+
i=1: tank=0+(-2)=-2 < 0 → reset tank=0, start=2
18+
i=2: tank=0+(-2)=-2 < 0 → reset tank=0, start=3
19+
i=3: tank=0+(+3)=+3 ≥ 0 → continue
20+
i=4: tank=3+(+3)=+6 ≥ 0 → return start=3
21+
22+
Key insight: If total_gas ≥ total_cost, greedy start position works!
23+
"""
224

325
# Time: O(n)
426
# Space: O(1)

0 commit comments

Comments
 (0)