-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathgas_station.rb
33 lines (29 loc) · 941 Bytes
/
gas_station.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# https://leetcode.com/problems/gas-station/
#
# There are N gas stations along a circular route, where the amount of gas at
# station i is gas[i]. You have a car with an unlimited gas tank and it costs
# cost[i] of gas to travel from station i to its next station (i+1). You begin
# the journey with an empty tank at one of the gas stations.
#
# Return the starting gas station's index if you can travel around the circuit
# once, otherwise return -1.
#
# Note: The solution is guaranteed to be unique.
# @param {Integer[]} gas
# @param {Integer[]} cost
# @return {Integer}
def can_complete_circuit(gas, cost)
n = gas.size
sum, lbound, ubound = gas[0], -1, 0
while ubound - lbound != n
if sum - cost[ubound] >= 0
sum += - cost[ubound] + gas[ubound + 1]
ubound += 1
else
sum += - cost[lbound] + gas[lbound]
lbound -= 1
end
end
sum += - cost[lbound]
sum < 0 ? -1 : (lbound + 1 + n) % n
end