Write an algorithm using an IF...THEN statement for deciding whether to refuel a car
while driving along the motorway.
Answers
Answer:
Time complexity is calculated according to number of operation executed. Its not matter how many nested loop in there...
Your first while loop executed until currentPosition <= n and nested while loop executed until currentPosition <= n && x[currentPosition + 1] – x[lastPosition] <= L.. In this loop you increases currentPostion. So there is no possibility your total operation exceed n times.
Example:
array[0, 10, 20, 30] and L = 50..
For this case your first while loop true for 1st step.. You nested loop true for 4 steps. Then at 2nd step your first while loop false... So there executed N step...
Thats why your code complexiy : O ( N )...
Doubt 2:
To minimize refill , you need to go far as you can with current fuel.If you cross k station with current fuel then there is no need to fill tank at 1 to k-1 stations..At every station u need to check, is it possible to go next station with current fuel. If you can go from current station to next station with current fuel, then refill tank at current station is redundant.
Doubt 3:
There is many ways to solve a problem... Here is another one:
numRefills = 0
currentPosition = 0
currentFuel = L
while(currentPosition <= n){
if (currentFuel < x[currentPosition+1] - x[currentPosition]) {
currentFuel = L;
numRefills++;
}
currentFuel -= (x[currentPosition+1] - x[currentPostion]);
if ( currentFuel < 0 )
return Impossible;
currentPosition++;
}
return numRefills
Explanation:
Hey
plz mark as brainlist