134. Gas Station

https://leetcode.com/problems/gas-station/discuss/42591/java-greedy-solution

 

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

 

posted @ 2018-12-06 12:13  jasoncool1  阅读(199)  评论(0编辑  收藏  举报