File tree Expand file tree Collapse file tree 3 files changed +48
-39
lines changed
solution/0100-0199/0134.Gas Station Expand file tree Collapse file tree 3 files changed +48
-39
lines changed Original file line number Diff line number Diff line change @@ -151,23 +151,26 @@ public:
151
151
152
152
```go
153
153
func canCompleteCircuit(gas []int, cost []int) int {
154
- n := len(gas)
155
- i, j := n-1, n-1
156
- cnt, s := 0, 0
157
- for cnt < n {
158
- s += gas[j] - cost[j]
159
- cnt++
160
- j = (j + 1) % n
161
- for s < 0 && cnt < n {
162
- i--
163
- s += gas[i] - cost[i]
164
- cnt++
154
+ totalGas, totalCost := 0, 0
155
+ tank := 0
156
+ startStation := 0
157
+
158
+ for i := 0; i < len(gas); i++ {
159
+ totalGas += gas[i]
160
+ totalCost += cost[i]
161
+ tank += gas[i] - cost[i]
162
+
163
+ if tank < 0 {
164
+
165
+ startStation = i + 1
166
+ tank = 0
165
167
}
166
168
}
167
- if s < 0 {
169
+
170
+ if totalGas < totalCost {
168
171
return -1
169
172
}
170
- return i
173
+ return startStation
171
174
}
172
175
```
173
176
Original file line number Diff line number Diff line change @@ -142,23 +142,26 @@ public:
142
142
143
143
```go
144
144
func canCompleteCircuit(gas []int, cost []int) int {
145
- n := len(gas)
146
- i, j := n-1, n-1
147
- cnt, s := 0, 0
148
- for cnt < n {
149
- s += gas[j] - cost[j]
150
- cnt++
151
- j = (j + 1) % n
152
- for s < 0 && cnt < n {
153
- i--
154
- s += gas[i] - cost[i]
155
- cnt++
145
+ totalGas, totalCost := 0, 0
146
+ tank := 0
147
+ startStation := 0
148
+
149
+ for i := 0; i < len(gas); i++ {
150
+ totalGas += gas[i]
151
+ totalCost += cost[i]
152
+ tank += gas[i] - cost[i]
153
+
154
+ if tank < 0 {
155
+
156
+ startStation = i + 1
157
+ tank = 0
156
158
}
157
159
}
158
- if s < 0 {
160
+
161
+ if totalGas < totalCost {
159
162
return -1
160
163
}
161
- return i
164
+ return startStation
162
165
}
163
166
```
164
167
Original file line number Diff line number Diff line change 1
1
func canCompleteCircuit (gas []int , cost []int ) int {
2
- n := len (gas )
3
- i , j := n - 1 , n - 1
4
- cnt , s := 0 , 0
5
- for cnt < n {
6
- s += gas [j ] - cost [j ]
7
- cnt ++
8
- j = (j + 1 ) % n
9
- for s < 0 && cnt < n {
10
- i --
11
- s += gas [i ] - cost [i ]
12
- cnt ++
2
+ totalGas , totalCost := 0 , 0
3
+ tank := 0
4
+ startStation := 0
5
+
6
+ for i := 0 ; i < len (gas ); i ++ {
7
+ totalGas += gas [i ]
8
+ totalCost += cost [i ]
9
+ tank += gas [i ] - cost [i ]
10
+
11
+ if tank < 0 {
12
+
13
+ startStation = i + 1
14
+ tank = 0
13
15
}
14
16
}
15
- if s < 0 {
17
+
18
+ if totalGas < totalCost {
16
19
return - 1
17
20
}
18
- return i
21
+ return startStation
19
22
}
You can’t perform that action at this time.
0 commit comments