134. Gas Station

网友投稿 273 2022-12-01

134. 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.

class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { if (gas == null || cost == null || gas.length == 0 || cost.length == 0) { return -1; } int sum = 0; int total = 0; int index = -1; for(int i = 0; i

class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { int currentNetSum = 0; int startIdx = -1; int totalNetDiff = 0; for(int idx = 0; idx < gas.length; idx++) { int currentDiff = gas[idx] - cost[idx]; currentNetSum += currentDiff; totalNetDiff += currentDiff; if(currentNetSum < 0) { currentNetSum = 0; startIdx = -1; continue; } startIdx = startIdx == -1 ? idx: startIdx; } return startIdx != -1 && totalNetDiff >= 0 ? startIdx: -1; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:14. Longest Common Prefix
下一篇:小朋友学C语言(3):整数、浮点数、字符
相关文章

 发表评论

暂时没有评论,来抢沙发吧~