Gas station Leetcode Python

Source: Internet
Author: User

There was N gas stations along a circular route, where the amount of gas at station I was gas[i].


You had a car with an unlimited gas tank and it costs cost[i] of the gas-to-travel from station I to its next station (I+1). You begin the journey with a 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.

First of all to determine the total oil enough consume, if the total oil is less than the total consumption that must be out of the way. Second, the process of whether the remaining oil will be less than 0, if less than 0 that can only start from the next station. Walk through it to get an answer.

1. Compare total gas and total cost, if total gas<total cost

Return-1

2. Iterate the whole station, Rest+=gas[i]-cost[i] If rest<0, search start from the next I

Return station

Class solution:    # @param gas, a list of integers    # @param cost, a list of integers    # @return an integer    de F Cancompletecircuit (self, gas, cost):        if sum (gas) <sum (cost):            return-1        Else:            pre=0            rest=0            station=0 for            index in range (len):                Rest+=gas[index]-cost[index]                if rest<0:                    pre+= Rest                    rest=0                    station=index+1        return station        


Gas station Leetcode Python

Related Article

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.