Gas Station 加油站問題【oj】
問題描述:
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.
常規來做會是依次判斷,個人做題是也是,後來超時了囧。改進的核心是需要知道1. sum(gas-cost)>= 0時一定有解;2.向前累積和,如果某個位置的和為負,則該解一定在其後。
問題可以轉換為求rest[i] = gas[i] - cost[i] + rest[i-1],每一次遇到rest[i] < 0;則捨棄前面的部分,從i+1繼續統計,使得從該位起其後的rest為正。
時間複雜度為O(n),為了節省空間,所以不需要rest陣列,直接使用rest。
相關程式碼:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { int size = gas.size(); int total = 0; int rest = 0; int end = -1; //最後一個rest為負的位置 for(int index = 0; index < size; index++) { rest += gas[index] - cost[index]; total += gas[index] - cost[index]; if(rest < 0) { end = index; rest = 0; } } if(total < 0 ) return -1; else return end + 1; }
個人感想:這個題真的很考邏輯,核心:需要知道total > 0 時一定有解,又由於解唯一,所以累計和為負則前面的index均不可能作為起始點,重新累計。個人覺得是找到陣列中子序列和最大的變形。嘻嘻加油!