[Leetcode] gas-station problem

Title description:

There are n gas stations on the ring road, and the gasoline volume of the i-th gas station is gas[i]. You have a car, and its fuel tank can be filled with unlimited gasoline. The cost of walking from gas station i to the next gas station (i+1) is cost[i]. You start from a gas station and there is no gasoline in the tank at the beginning. Ask from which gas station you can walk around the ring road. Return the subscript of the gas station, or -1 if there is no answer.

Note: The answer is guaranteed to be unique.

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.

problem analysis:

1. By subtracting the total amount of gasoline from all gas stations, it can be judged whether it is possible to walk a circle on the ring road. If not, return -1;

2. Assuming that the remaining amount of fuel arriving at the i-th gas station is sum, then add the amount of gasoline gas[i] at the i-th gas station and subtract the amount of gas spent to go to the next station (i+1) cost[ i], it can be judged whether the next gas station can be reached from the i-th gas station;

3. If the current position does not support moving forward, change to the next gas station as the starting point;

4. If there is a solution, then it is the only solution, and return to the location of the gas station (counting from 1).

Analysis of Algorithms:

Greedy thinking can be used to solve this problem, and the core is the search for start. Starting from the first gas station, if you encounter a non-compliance with the requirements, then start from the gas station that does not meet the requirements. In view of the previous calculations, it can be known that the first gas station is reachable to this location, and if you start from this location, you can go Reaching the end means that you can walk on the roundabout. The algorithm time complexity is O(n).

Coding implementation:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int sum = 0, start = -1, total = 0;
		for( int i=0; i<gas.length; i++) {
			sum += gas[i]-cost[i];
			total += gas[i]-cost[i];
			if(sum<0) {
				sum = 0;
				start = i;
		return total>=0 ? start+1:-1;


Guess you like

Origin blog.csdn.net/VinWqx/article/details/104907324