Sunday, November 24, 2013

LeetCode Problem : Gas Station

Problem



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.

Code

int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    int n = gas.size();
    for(int i = 0;i < n; ++i){
        int sum = 0;
        int j = 0;
        for(;j < n; ++j){
            int k = (i + j < n) ? (i + j) : (i + j - n);
            sum += (gas[k] - cost[k]);
            if(sum < 0)
                break;
        }
        if(j == n)
            return i;
    }
    return -1;  
}

No comments:

Post a Comment