ProgrammingHardAccenture · Cognizant
Gas stations on a circle: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Station i gives gas[i] and then costs cost[i] to leave for station i+1. The total gas equals the total cost, so a full tour exists from exactly one start. The procedure below finds it. What is printed?
Gas stations on a circle: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Station i gives gas[i] and then costs cost[i] to leave for station i+1. The total gas equals the total cost, so a full tour exists from exactly one start. The procedure below finds it. What is printed?
total = 0; tank = 0; start = 0
for i = 0 to 4
tank = tank + gas[i] - cost[i]
total = total + gas[i] - cost[i]
if tank < 0 then start = i + 1; tank = 0
end for
Print start- A. 0
- B. 3
- C. 2
- D. 4
Correct answer: B. 3
Once the tank goes negative no station between the old start and i can start a valid tour, so the start moves to i+1 and the tank resets. Starting at 0 ignores the failed stretch, resetting to i instead of i+1 restarts a station too early, and not resetting the tank carries a deficit forward.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Ropes are to be merged into one. Merging two ropes of lengths a and b costs a + b and yields one rope of length a + b. Ropes have lengths…
- Stock prices by day: 3, 8, 2, 9, 1, 6. One share may be bought once and sold once later (later day only). The procedure below runs. What…
- Currency notes are paid out greedily from the largest denomination down, using as many notes of each denomination as possible. For amount…
- A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number…
- The same stack method is applied to the string 5317 with exactly 2 digits deleted, but now the aim is the LARGEST number. The procedure…
- Children have greed values 7, 8, 9, 10 and cookies have sizes 5, 6, 7, 8, 8. A child is content if the cookie given is at least his greed…