ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

What is printed?
import heapq
def refuel(target, start, stations):
    h = []
    i = 0
    fuel = start
    stops = 0
    while fuel < target:
        while i < len(stations) and stations[i][0] <= fuel:
            heapq.heappush(h, -stations[i][1])
            i += 1
        if not h:
            return -1
        fuel += -heapq.heappop(h)
        stops += 1
    return stops
print(refuel(100, 10, [[10, 60], [20, 30], [30, 30], [60, 40]]), refuel(100, 1, [[10, 100]]))
  1. A. 2 -1
  2. B. 1 -1
  3. C. 2 0
  4. D. 3 -1

Correct answer: A. 2 -1

Greedy refuelling takes the largest station passed so far whenever fuel runs short. The first case needs two stops, and in the second the station at 10 can never be reached with fuel 1.

More Python Programming questions

Exams that ask this topic