Monday, January 19, 2015

Gas Station (LeetCode Greedy)

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

Idea: If the sum of the gas[] is larger than the sum of the cost[], the roundtrip can be fulfilled. However, the start point can not be anywhere, since partial of the trajectory may be quite "tough" (partial sum of cost> partial sum of gas). As said in Shelley's "Ode to the west wind", "If Winter comes, can Spring be far behind? ", we need to locate the end of the winter.

Start from a round point of the trip, we may face a series of continuous "tough" roads. However, since we know the round trip can be fulfilled, that means starting from the end of last "tough" roads we encountered, we can accomplish the whole trip, otherwise the whole trip can not be finished. This can be proved easily by contradiction.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public int canCompleteCircuit(int[] gas, int[] cost) {  
     int sum=0;  
     int total=0;  
     int breakPoint=-1;  
     for(int i=0;i<gas.length;i++)  
     {  
       sum+=gas[i]-cost[i];  
       total+=gas[i]-cost[i];  
       if(sum<0)  
       {  
         breakPoint=i;  
         sum=0;  
       }  
     }  
     if(total>=0)  
       return breakPoint+1;  
     else  
       return -1;  
   }  
 }  

No comments:

Post a Comment