File tree Expand file tree Collapse file tree 1 file changed +20
-10
lines changed
Expand file tree Collapse file tree 1 file changed +20
-10
lines changed Original file line number Diff line number Diff line change 44 * @return {number }
55 */
66var canCompleteCircuit = function ( gas , cost ) {
7- let total = 0 , current = 0 , start = 0 ;
8- for ( let i = 0 ; i < gas . length ; i ++ ) {
9- let diff = gas [ i ] - cost [ i ] ;
10- total += diff ;
11- current += diff ;
12- if ( current < 0 ) {
13- start = i + 1 ;
14- current = 0 ;
7+ // two pointers
8+ let start = 0 ;
9+ let end = 0 ;
10+ let sum = gas [ start ] - cost [ start ] ;
11+ const len = gas . length ;
12+
13+ while ( start < len ) {
14+ if ( sum < 0 ) {
15+ start = end + 1 ;
16+ end = start ;
17+ sum = gas [ start ] - cost [ start ] ;
18+ } else {
19+ if ( end - start === len - 1 ) return start ;
20+ end ++ ;
21+ let endIdx = end % len ;
22+ sum += gas [ endIdx ] - cost [ endIdx ] ;
23+ }
24+
1525 }
16- }
17- return total >= 0 ? start : - 1 ;
26+ return - 1 ;
27+
1828} ;
You can’t perform that action at this time.
0 commit comments