题目:
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an 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.
思路1:暴力解决,即遍历
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
for(int i=0;i<n;i++)
{
int rest = 0;
int j;
for(j = 0;j<n;j++)
{
if(gas[(i+j)%n]+rest < cost[(i+j)%n])
{
break;
}
rest = gas[(i+j)%n]+rest-cost[(i+j)%n];
}
if(j==n){return i;}
}
return -1;
}
}
显然O(n^2) TLE
思路2:动态规划
即求数组的最大连续子串。
由于这是一个循环的数组,那么最大连续(可循环)子串 = max{最大连续子串(不循环),total-最小连续子串}。最大连续子串和的算法很是精度
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int maxPos = 0,maxValue = Integer.MIN_VALUE,maxCurSum = 0;
int minPos = 0,minValue = Integer.MAX_VALUE,minCurSum = 0;
int total = 0;
for(int i=0;i<n;i++)
{
total += (gas[i]-cost[i]);
int tempMaxPos = maxPos;
if(gas[i]-cost[i] > maxCurSum+gas[i]-cost[i])
{
maxCurSum = gas[i]-cost[i];
tempMaxPos = i;
}else
maxCurSum += gas[i]-cost[i];
if(maxCurSum > maxValue)
{
maxPos = tempMaxPos;
maxValue = maxCurSum;
}
if(gas[i]-cost[i] < minCurSum+gas[i]-cost[i])
{
minCurSum = gas[i]-cost[i];
}else
minCurSum += gas[i]-cost[i];
if(minCurSum < minValue)
{
minPos = i;
minValue = minCurSum;
}
}
if(maxValue >= (total-minValue) && total>=0)
{
//System.out.println(maxPos);
return maxPos;
}else
if(maxValue < (total-minValue) && total>=0)
{
System.out.println(minPos);
return (minPos+1)%n;
}
return -1;
}
思路3:
贪心算法。最为直接。和小于0就不符合要求。
a[i]+..+a[j]<0,则不可能存在p在(i,j)之间使得a[p]+..+a[j]>=0;
反证法:
如果a[p]+..+a[j]>=0 ,则a[i]+..+a[p-1]<0
这显然与我的代码矛盾,因为我每次都对sum<0时,sum置0。
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total = 0;
int sum = 0;
int pos = 0;
for(int i=0;i<gas.length;i++)
{
total += gas[i]-cost[i];
sum += gas[i]-cost[i];
if(sum<0)
{
sum = 0;
pos = i+1;
}
}
if(total<0)
return -1;
else
return pos;
}
}