Sunday, January 18, 2015

Gas Station

Q:
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.

T:
This problem is tricky to solve. Assume we start from station 0, then at some point, say station i, the gas may become negative. So we need to assume we start from the station i, and see whether when we reach station n there is enough gas left to continue the loop from station 0 to station i-1.

A:


class Solution {
public:
    int canCompleteCircuit(vector< int > &gas, vector< int > &cost) {
        int previous = 0;
        int rest = 0;
        int index = 0;
        for(int i=0; i < gas.size(); i++) {
            rest += gas[i] - cost[i];
            if (rest < 0) {
                previous += rest;
                rest = 0;
                index = i+1;
            }
        }
        if (previous + rest >= 0) {
            return index;
        } else {
            return -1;
        }
    }
};

No comments:

Post a Comment