Leetcode -- gas station

Source: Internet
Author: User

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 ;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.