Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a min-heap of size = ladders). How far (index) can you get?

Problem: Walk along buildings; climbing up by d costs d bricks or one ladder (going down is free). Use ladders on the largest climbs (a min-heap of size = ladders). How far (index) can you get?
import heapq
def furthest(h, bricks, ladders):
    heap = []
    for i in range(len(h) - 1):
        d = h[i+1] - h[i]
        if d > 0:
            heapq.heappush(heap, d)
            if len(heap) > ladders:
                bricks -= heapq.heappop(heap)
                if bricks < 0: return i
    return len(h) - 1
print(furthest([3, 8, 4, 10, 11, 6, 12, 20], 6, 2))
What is printed?
  1. A. 7
  2. B. 6
  3. C. 5
  4. D. 2

Correct answer: B. 6

Climbs are 5, 6, 1, 6, 8. Ladders stay on the two largest so far: the climb 1 is paid with bricks (5 left), the next 6 pushes the 5 onto bricks (0 left), and the final 8 forces a 6 onto bricks, which runs out, so you stop at index 6. Returning i + 1 gives 7, spending ladders on the first climbs gives 5, and forgetting the ladders altogether stops at index 2.

More Coding Interview Problems questions

Exams that ask this topic