File tree Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Expand file tree Collapse file tree 2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 134. Gas Station
3
+ * https://leetcode.com/problems/gas-station/
4
+ * Difficulty: Medium
5
+ *
6
+ * There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
7
+ *
8
+ * You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to
9
+ * its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
10
+ *
11
+ * Given two integer arrays gas and cost, return the starting gas station's index if you can travel around
12
+ * the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is
13
+ * guaranteed to be unique
14
+ */
15
+
16
+ /**
17
+ * @param {number[] } gas
18
+ * @param {number[] } cost
19
+ * @return {number }
20
+ */
21
+ var canCompleteCircuit = function ( gas , cost ) {
22
+ let total = 0 , tank = 0 , index = 0 ;
23
+
24
+ for ( let i = 0 ; i < gas . length ; i ++ ) {
25
+ tank += gas [ i ] - cost [ i ] ;
26
+ total += gas [ i ] - cost [ i ] ;
27
+ if ( tank < 0 ) {
28
+ tank = 0 ;
29
+ index = i + 1 ;
30
+ }
31
+ }
32
+
33
+ return total >= 0 ? index : - 1 ;
34
+ } ;
Original file line number Diff line number Diff line change 78
78
121|[ Best Time to Buy and Sell Stock] ( ./0121-best-time-to-buy-and-sell-stock.js ) |Easy|
79
79
128|[ Longest Consecutive Sequence] ( ./0128-longest-consecutive-sequence.js ) |Medium|
80
80
133|[ Clone Graph] ( ./0133-clone-graph.js ) |Medium|
81
+ 134|[ Gas Station] ( ./0134-gas-station.js ) |Medium|
81
82
136|[ Single Number] ( ./0136-single-number.js ) |Easy|
82
83
141|[ Linked List Cycle] ( ./0141-linked-list-cycle.js ) |Easy|
83
84
142|[ Linked List Cycle II] ( ./0142-linked-list-cycle-ii.js ) |Medium|
You can’t perform that action at this time.
0 commit comments