134 gas station (Array; DP)

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 of gas to travel from station cost[i] 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.

Ideas:

1. Can I travel around? = as long as gas[] plus total and-cost[] plus Total and > 0, will be able to. = = requires an int to calculate the sum of gas[]-cost[]

2. How do I find the starting point? If the oil is not enough at a certain station, then the starting point must be re-searched from behind it. = = requires an int to record the amount of oil from the starting point found so far

Time complexity O (n)

classSolution { Public:    intCancompletecircuit (vector<int> &gas, vector<int> &Cost ) {        intsum =0, total =0, Len = Gas.size (), index =-1;  for(intI=0; i<len; i++) {sum+ = gas[i]-Cost[i]; Total+ = gas[i]-Cost[i]; if(Sum <0) {Index=i; Sum=0; }        }        returntotal>=0? index+1: -1; }};

134 gas station (Array; DP)

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.