layout: post title: Gas Station comments: true category: Algorithms tag: algorithm, leetcode, greedy —

Description

https://oj.leetcode.com/problems/gas-station/

Difficulty: 4.0/5.0

Solution

This is not a easy problem. First thing to clarify is that we can only go from (i+1)_{th}$$ station.

Then we can prove (details omitted) that

If , , but , then we cannot reach the station from any station in (i.e., ). This means that we cannot travel around starting from stations in

Here .

Therefore, the algorithm is that we start from gas station and we keep the current net gas in the tank , once the , we know that the stations that we have been before cannot be the starting stations. Then we clear the net gas and move to the next station and check.

If the total net gas is negative, then we do not have a solution, otherwise, we are guaranteed to be able to find a solution.

class Solution {
public:
	int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
		int sum = 0, totalSum = 0;
		int result = 0;
		for (int i = 0; i < gas.size(); ++ i){
			sum += gas[i] - cost[i];
			if (sum < 0){
				result = i+1;
				sum = 0;
			}
			totalSum += gas[i] - cost[i];
		}
		if (totalSum < 0)
			return - 1;
		return result;
	}
};