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.

思路: 从第一个点开始,查看可以允许的长度,如果和为负数,则重新开始计数;并且要记录总路径之和,只有总路径之和大于等于0,才能够保证可以转一圈。

JAVA 代码:

  1. public int canCompleteCircuit(int[] gas, int[] cost) {
  2. int start = 0;
  3. int sum = 0; // judge the current start is ok
  4. int total = 0; // ensure the circle is ok
  5. for(int i = 0 ;i<gas.length;i++) {
  6. sum += gas[i] - cost[i];
  7. total += gas[i] - cost[i];
  8. if(sum < 0) {
  9. start = i+1;
  10. sum = 0;
  11. }
  12. }
  13. if(total<0) return -1;
  14. return start;
  15. }
posted @ 2014-07-04 14:13  purejade  阅读(127)  评论(0)    收藏  举报