leetcode@ [134] gas station (Dynamic programming)

Source: Internet
Author: User

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

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.

classSolution { Public:    intCancompletecircuit (vector<int>& Gas, vector<int>&Cost ) {        intn =gas.size (); if(n = =0)return-1; if(n = =1) {            if(gas[0]-cost[0] >=0)return 0; return-1; } Vector<int>dif; dif.clear ();  for(intI=0; i<n;++i) Dif.push_back (Gas[i]-Cost[i]);  for(intI=0; i<n-1; ++i) Dif.push_back (Gas[i]-Cost[i]); Vector<int> Sum (2*n-1,0); Vector<int> DP (2*n-1,0); sum[0] = dif[0]; dp[0] =1;  for(intI=1;i<2*n-1;++i) {if(sum[i-1] <0) {Sum[i]=Dif[i]; Dp[i]=1; }            Else{Sum[i]= sum[i-1] +Dif[i]; Dp[i]= dp[i-1] +1; }                        if(Dp[i] = = n && sum[i] >=0)returni-n+1; }                return-1; }};
View Code

[email protected] [134] Gas station (Dynamic programming)

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.