You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/medium/readme.md
+51Lines changed: 51 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -1032,6 +1032,57 @@ Put the code below in main.rs and run `cargo run`
1032
1032
println!("result: {:?}", result);
1033
1033
```
1034
1034
1035
+
# 134. Gas Station
1036
+
1037
+
## Description
1038
+
1039
+
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
1040
+
1041
+
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
1042
+
1043
+
Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
1044
+
1045
+
## Examples
1046
+
1047
+
```text
1048
+
Input: gas = [1,2,3,4,5], cost = [3,4,5,1,2]
1049
+
Output: 3
1050
+
1051
+
Explanation:
1052
+
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
1053
+
Travel to station 4. Your tank = 4 - 1 + 5 = 8
1054
+
Travel to station 0. Your tank = 8 - 2 + 1 = 7
1055
+
Travel to station 1. Your tank = 7 - 3 + 2 = 6
1056
+
Travel to station 2. Your tank = 6 - 4 + 3 = 5
1057
+
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
1058
+
Therefore, return 3 as the starting index.
1059
+
```
1060
+
1061
+
```text
1062
+
Input: gas = [2,3,4], cost = [3,4,3]
1063
+
Output: -1
1064
+
1065
+
Explanation:
1066
+
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
1067
+
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
1068
+
Travel to station 0. Your tank = 4 - 3 + 2 = 3
1069
+
Travel to station 1. Your tank = 3 - 3 + 3 = 3
1070
+
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
1071
+
Therefore, you can't travel around the circuit once no matter where you start.
0 commit comments