Input
(1) the maximum distance that a car can travel with a full tank: L km;
(2) an integer array, [0, x1, x2, …, xn, xn+1], each integer represents the distance between a location and a source point A. The first integer is 0, which is the distance between A and A. The second distance x1, represents the distance between the first gas station and A. There are n gas stations between A and B (the destination). xn is the distance between the last gas station and A, and xn+1 is the distance between B and A.
(3) n, which is the number of gas stations.
Output
The minimum number of refills to get from A to B
Code
numRefills = 0
currentPosition = 0
while(currentPosition <= n){
lastPosition = currentPosition
while(currentPosition <= n && x[currentPosition + 1] – x[lastPosition] <= L) {
currentPosition++;
}
if (currentPosition == lastPosition) return IMPOSSIBLE;
if (currentPosition <= n) numRefills ++;
}
return numRefills
My doubts are:
- Why is the time-complexity of the above code is O(n)? shouldn't it be O(n^2) at least because of nested while loops?
- How to prove that "Refilling at farthest reachable gas" is a safe move?
- Are there any alternatives to writing the same code but using for loop?
(In short, I understood the logic but I am not able to compute it)
Any resources/help/hint/guidance is greatly appreciated!