File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/gas-station/
3
+ * Primary idea: use currentSum and total to keep track of the gas and cost,
4
+ * change start index when currentSum is less than 0
5
+ *
6
+ * Time Complexity: O(n), Space Complexity: O(1)
7
+ *
8
+ */
9
+
10
+ class GasStation {
11
+ func canCompleteCircuit( _ gas: [ Int ] , _ cost: [ Int ] ) -> Int {
12
+ guard gas. count == cost. count else {
13
+ return - 1
14
+ }
15
+
16
+ var currentSum = 0
17
+ var total = 0
18
+ var startIdx = 0
19
+
20
+ for (i, curtGas) in gas. enumerated ( ) {
21
+ currentSum += ( curtGas - cost[ i] )
22
+ total += ( curtGas - cost[ i] )
23
+
24
+ if currentSum < 0 {
25
+ startIdx = i + 1
26
+ currentSum = 0
27
+ }
28
+ }
29
+
30
+ if total < 0 {
31
+ return - 1
32
+ }
33
+ return startIdx
34
+ }
35
+ }
You can’t perform that action at this time.
0 commit comments