There areNGas stations along a circular route, where the amount of gas at StationIIsGas [I]
.
You have a car with an unlimited gas tank and it costsCost [I]
Of gas to travel from StationITo 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.
Original question link: https://oj.leetcode.com/problems/gas-station/
Question: There are N gas stations in a ring, and the station I have gas [I] oil.
You have a car with an infinite fuel tank. It consumes cost [I] oil from station I to station I + 1. You start from one of the stations with an empty fuel tank. If you turn around, the index of the starting station is returned, otherwise-1 is returned.
Idea: calculate the difference between the gas station fuel and the fuel consumed by the car when the car arrives at each gas station. If the difference is less than 0, it indicates that the car should start at least from the next stop, if you leave this site, you cannot reach the next stop. If the total deviation is less than 0, the car cannot complete a lap.
Public int cancompletecircuit (INT [] gas, int [] cost) {int minus = 0, total = 0, Index =-1; for (INT I = 0; I <gas. length; I ++) {minus + = gas [I]-cost [I]; Total + = minus; If (minus <0) {Index = I; minus = 0 ;}} return total <0? -1: index + 1 ;}