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)