Friday, September 19, 2014

[Leetcode] 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.
Analysis:
  • example: gas: [1,2,3,4,5], cost [3,4,5,1,2]
  • Diff is [-2,-2,-2, 3, 3]
  • Diff accumulation from right to left is [0,2,4,6,3] and should choose the idx with max diff is the station to start
  • The accumulation is the remaining gas at station 5 when travel beginning from station i ( 1 <= i <= 5)
  • We should choose the idx with the max value as the start station.



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

No comments:

Post a Comment