Leetcode Gas Station

来源:互联网 发布:批判性思维工具 知乎 编辑:程序博客网 时间:2024/05/16 15:53

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.


Difficulty: Medium


Solution: tricky greedy problem


To solve this problem, we need to understand and use the following 2 facts:
1) if the sum of gas >= the sum of cost, then the circle can be completed.
2) if A can not reach C in a the sequence of A-->B-->C, then B can not make it either.


public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        int len = gas.length;        int ans = 0, remaining = 0, totalRemaining = 0;        for(int i = 0; i < len; i++){            totalRemaining += gas[i] - cost[i];            if(remaining < 0){                ans = i;                remaining = gas[i] - cost[i];            }            else{                remaining += gas[i] - cost[i];            }        }        if(remaining < 0 || totalRemaining < 0) return -1;        return ans;    }}


0 0