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

我的提交:

/*17.3.31
*有点像最大连续子序列和的动态规划解法
*如果total大于0,从左到右扫描,一定能切分出一个和大于0的区间(起点为i,终点为数组的结尾)
*如-1,-2,2,3,-6,10
*-1被切开,-2被切开,3,4,-6被切开,10大于0,所以以10为起点!
*换一个顺序-6,10,-1,-2,2,3
*-6被切开,10~3大于0,结果还是以10为起点。
*/
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = 0,total = 0;
        for(int i=0,tank=0;i<gas.length;i++){
            if(tank<0){
                tank = gas[i] - cost[i];
                start = i;
            }
            else{
                tank += gas[i] - cost[i];
            }
            total += gas[i] - cost[i];
        }
        return total<0?-1:start;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • LeetCode 134 Gas Station There are N gas stations along a...
    ShuiLocked阅读 539评论 0 0
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,778评论 0 33
  • 一家公司想要其营销组合中的产品要素,可以通过产品线拓展来延伸产品,或者进行产品线填补。 品牌常常需要和其他品牌联合...
    paidaren阅读 130评论 0 1
  • 3.8号国际妇女节悄然而至,今年我看到各大购物网站打出了娘娘节、女王节的宣传来,甚是为劳动人民的智慧感到骄傲。娘娘...
    羊白羊阅读 346评论 0 1
  • 自动化部署系统将集群的所有状态保存在几个文件中,即使将集群完全摧毁,通过这些配置文件,可以很快恢复完全一样的集群出...
    zeoleeee阅读 223评论 0 1