[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:

http://blog.csdn.net/kenden23/article/details/14106137

 1 public class Solution {
 2     public int canCompleteCircuit(int[] gas, int[] cost) {
 3         int N=gas.length;
 4         int i=0;
 5         int sum=0;
 6         int total=0;
 7         int j=-1;
 8         while(i<N){
 9             sum+=gas[i]-cost[i];
10             total+=gas[i]-cost[i];
11             if(sum<0){
12                 j=i;
13                 sum=0;
14             }
15             ++i;
16         }
17         if(total<0)
18             return -1;
19         else
20             return j+1;
21     }
22 }

 

posted @ 2014-11-15 08:27  Phoebe815  阅读(186)  评论(0编辑  收藏  举报