Skip to content

Commit 984c931

Browse files
committed
Add solution #134
1 parent f5362f3 commit 984c931

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

0134-gas-station.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy|
7979
128|[Longest Consecutive Sequence](./0128-longest-consecutive-sequence.js)|Medium|
8080
133|[Clone Graph](./0133-clone-graph.js)|Medium|
81+
134|[Gas Station](./0134-gas-station.js)|Medium|
8182
136|[Single Number](./0136-single-number.js)|Easy|
8283
141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy|
8384
142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium|

0 commit comments

Comments
 (0)