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(vector<int>& gas, vector<int>& cost) {
        int sum = 0;
        int total = 0;
        int j = -1;
        int n = gas.size();
        
        for(int i=0;i<n;i++)
        {
            sum += gas[i] - cost[i];
            total += gas[i] - cost[i];
            if(sum<0)
            {
                sum = 0;
                j = i;
            }
        }
        if(total<0)
          return -1;
        return j+1;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,788评论 0 33
  • LeetCode 134 Gas Station There are N gas stations along a...
    ShuiLocked阅读 539评论 0 0
  • 常听人说一孕傻三年,却没听说过一婚降智商的,想本小姐婚前也好歹是独立知性的白领一枚,为什么婚后却成了他的二货媳妇,...
    梦悠悠阅读 300评论 0 0
  • 人总是这样 被误解 解释 掩饰 真正懂你的人 不需要解释 抑或是掩饰
    瑞秋小仙女阅读 178评论 0 0
  • 1.Rain Man。 为什么天才总是要与孤独症为伍?德雷克、周炜、维根斯坦、霍金,甚至比尔盖茨、牛顿、爱因斯坦。...
    高小花0218阅读 168评论 0 0