134. Gas Station

Description

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.

Solution

DP, time O(n), space O(1)

Two things:

  • If car starts at A and can not reach B. Any station between A and B can not reach B.(B is the first station that A can not reach.)
  • If the total number of gas is bigger than the total number of cost. There must be a solution.

把gas[i] - cost[i]计算出来得到新的arr[],然后感觉就变成了最经典的MaxSubarraySum的变种。累加的sum如果变成负值,就直接丢掉,以下一个起点开始重新累加。

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = 0;
        int tank = 0;
        int total = 0;
        
        for (int i = 0; i < gas.length; ++i) {
            if (tank < 0) {
                tank = 0;
                start = i;
            }
            tank += gas[i] - cost[i];
            total += gas[i] - cost[i];
        }
        
        return total < 0 ? -1 : start;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,181评论 0 10
  • LeetCode 134 Gas Station There are N gas stations along a...
    ShuiLocked阅读 3,471评论 0 0
  • 我终于开始惶恐 在拆开信笺的一刻 悔恨的泪水在心底翻涌 如浪如涛 是亏欠了过去一点慷慨 还是辜负了 熟悉而又...
    宗史纪书阅读 1,823评论 0 1
  • 简书,你好! 第一次看到你的名字,就莫名地喜欢了! 进来了!希望你能带给我更多的惊喜!! 我知道自己已经过了做梦的...
    云沐风阅读 1,459评论 1 1
  • 杭州4 起来喝茶 换衣又是磨蹭到九点多才出门,已然忘了怎么坐上公交去到象山校区,只记得下来时雨势不小,今天许姑娘的...
    姑姑的我阅读 1,715评论 0 0

友情链接更多精彩内容