Gas Station

LeetCode #134


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.

Example:

Note

Idea:

如果total gas超过total cost,就可以,否则不行。记录每次到达一个地方的时候tank剩下的gas,gas最少的那个位置就是起点。

Code:

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {

        int min_gas=INT_MAX;
        int min_indx=0;
        int curr_gas=0;
        int N=gas.size();

        for(int i=0; i<N; ++i){
            curr_gas = curr_gas + gas[i] - cost[i];
            if(curr_gas<min_gas){
                min_gas=curr_gas;
                // after arrive at next station, but before fill up
                min_indx=i+1; 
            }

        }

        if(curr_gas<0)
            return -1;
        else
            return min_indx%N; // could be start from 0

    }
};

results matching ""

    No results matching ""