Sunday, February 9, 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.
Solution:

If the circuit is possible, i.e. $\sum \text{gas}\geq \sum \text{cost}$. Then once computed the minimum extra gas needed for the circular route, the minimum extra gas if we start on the next position is the same but not counting the previous position.

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) 
    {
        int sumTillNow = 0;
        int min = Integer.MAX_VALUE;
        int pos = -1;
        for(int i=0; i<gas.length; i++)
        {
            sumTillNow += gas[i] - cost[i];
            if(sumTillNow < min)
            {
                min = sumTillNow;
                pos = i;
            }
        }
        if (sumTillNow>=0)
            return (pos + 1) % gas.length;
        else
            return -1;
    }
}

No comments :

Post a Comment