Leetcode-gas station-gas station-Maximum SUBSTRING algorithm application

Source: Internet
Author: User

https://oj.leetcode.com/problems/gas-station/

Calculate the refueling difference for each petrol station diff[]. Gets an array. From the greedy point of view, if we find a maximum substring, then starting from his starting L, can go straight ahead and accumulate the largest amount of petrol.

One conjecture is: If the petrol is not enough to go through the whole process, then no matter where you can go through the whole process.

Can disprove: If starting from P can go through the whole process. Then the molecular string from P to L will be greater than 0, and this molecule string plus l start maximal substring can make the substring larger. Then with the maximum substring starting from l the contradiction. So there's no such p.

Therefore, using the maximum substring algorithm to find the maximum substring of the beginning L, and then perform a simulation, you can determine whether to complete the whole process.

classSolution { Public:    intn,m; intCancompletecircuit (vector<int> &gas, vector<int> &Cost ) {N=gas.size (); Vector<int> d=Gas ;  for(intI=0; i<n;i++) d[i]-=Cost[i]; intl=-1; intmaxs=-1; intcs=-1; intcl=-1;  for(intI=0;i<2*n;i++) {            intci=i%N; if(cs<0) {cs=d[ci];cl=CI;} Elsecs+=D[ci]; if(cs>maxs) {Maxs=CS; L=cl; }        }        intCur=0;  for(intI=0; i<n;i++) {            intcp= (l+i)%N; Cur+=D[CP]; if(cur<0)return-1; }        returnl; }};

Leetcode-gas station-gas station-Maximum SUBSTRING algorithm application

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.