DSA Factory
Free Heaps lessonsHeaps · Stage 3 · Mastery · Step 3

Ladders or bricks

Walk along buildings of different heights, climbing each rise with bricks or a ladder, and find the furthest you can get, by giving ladders to the biggest rises. About 20 minutes.

Ladders for the biggest rises

Walking from building to building, a drop or flat step costs nothing. A rise needs bricks equal to the rise, or one ladder, which covers any height. You have a number of bricks and ladders, and want to get as far as possible.

The best use of ladders is on the biggest rises, since that saves the most bricks. But you do not know in advance which rises will be the biggest.

Ladder: covers a rise of any height.
Best use: on the biggest rises.
In code
d = heights[i + 1] - heights[i]
if d > 0:
    heapq.heappush(heap, d)
Heights 3, 6, 4, 9, 5, 7 with 4 bricks and 1 ladder.
3
0
6
1
4
2
9
3
5
4
7
5
i

3 to 6 is a rise of 3. Give it the ladder.

Move 1 of 5

Decide with regret

Keep a min-heap of the rises that currently hold ladders. For each new rise, give it a ladder: push it. If that uses more than the ladders you own, take the smallest rise out of the heap and pay for it with bricks instead.

If the bricks become negative, you cannot afford the step: the answer is the building you are on. If you get through every step, the answer is the last building.

Too many ladders used: pay for the smallest with bricks.
Bricks below zero: stop at this building.
In code
if len(heap) > limit:
    removed = heapq.heappop(heap)
Quick check

Why pay with bricks for the smallest rise among those holding ladders?

  1. AIt costs the fewest bricks, so the ladders stay on the biggest rises
  2. BIt costs the most bricks
  3. CIt is the earliest rise
Show the answer

It costs the fewest bricks, so the ladders stay on the biggest rises. A ladder saves more bricks on a bigger rise.

Your problem

Furthest building you can reach

heights holds the heights of buildings in a row, and you have some bricks and some ladders. You start on building 0 and walk to the next building each step. If the next building is not taller, the step is free. If it is taller by d, you must spend d bricks or one ladder. Return the index of the furthest building you can reach.

Example
heights = [4, 2, 7, 6, 9, 14, 12], bricks = 5, ladders = 1 → 4

1 ≤ length of heights ≤ 100,000 · 1 ≤ heights[i] ≤ 1,000,000 · 0 ≤ bricks ≤ 1,000,000,000 · 0 ≤ ladders ≤ length of heights

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve