Problem
There are n gas stations along a circular route, where the amount of gas at the ith station is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays gas and cost, return the starting gas station’s index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If there exists a solution, it is guaranteed to be unique
Algorithm
Calculate the value of each point by using val[i] = gas[i] - cost[i]. Then find the start point with the max sum value. Then justify it on the circle until the front node the the start point.
Code
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
slen = len(gas)
val = [0] * slen
start, sum_v = 0, 0
for i in range(slen):
val[i] = gas[i] - cost[i]
sum_v = sum_v + val[i]
if sum_v < 0:
sum_v = 0
start = i+1
if start >= slen:
return -1
sum_v = 0
index = start
for i in range(slen):
sum_v = sum_v + val[index]
if sum_v < 0:
return -1
index = index + 1
if index >= slen:
index = 0
return start
本文介绍了一种解决汽车能否沿环路完成一圈旅行的问题算法。该算法通过计算每个加油站的净油量并找到最大累积值对应的起点,判断是否能从某一站出发完成环路旅行。
1054

被折叠的 条评论
为什么被折叠?



