Farthest Building You Can Reach
Walk as far along a row of buildings as your bricks and ladders allow, saving the ladders for the biggest climbs.
A row of buildings is given as an array heightsheights[i]ibricksladders
Example 1
Output: 4
Example 2
Output: 7
The Idea
Picture walking along the roofs of a street, from left to right. Stepping down onto a lower roof is easy, but a taller roof needs help: a ladder, or a pile of bricks to stand on, one brick for each unit of height. In Example 1 the heights are 4, 2, 7, 6, 9, 14 and 12, and you carry 5 bricks and 1 ladder.
Only three moves go up. Building 1 to building 2 is a climb of 5, building 3 to building 4 a climb of 3, and building 4 to building 5 another climb of 5. Together they need 13 units of height, more than 5 bricks and 1 ladder can cover. So where should the ladder go?
A ladder covers a climb of any size, while bricks are paid unit by unit. A ladder on the climb of 3 saves 3 bricks, but on a climb of 5 it saves 5. So a ladder is worth most on the biggest climbs, and the bricks should go to the small ones. Look at the picture below.
The ladder is on the first climb of 5, to building 2. The climb of 3 to building 4 is paid with bricks, which leaves 2 of the 5. The next climb, again 5, needs 5 bricks with only 2 left and no ladder, so building 4, marked "farthest", is the answer.
That plan was easy to make with every height in view. Walking along the street, though, you only see a climb when you reach it. Standing on building 1, you cannot know whether a bigger climb comes later. How can you decide where the ladder goes?
You do not have to decide at once. Put a ladder on each climb for now, and keep a list of the climbs that are on ladders. When that list holds one climb more than you have ladders, take its smallest climb off and pay for it with bricks, as if you had used bricks there all along.
In Example 1, the climb of 5 gets the ladder. At the climb of 3, the list holds 5 and 3, one more than the single ladder, so the 3 is paid with bricks. At the second climb of 5, the list holds 5 and 5, one of them moves to bricks, and 2 bricks cannot pay for it.
So at every building, the list holds the biggest climbs seen so far, one for each ladder, and bricks pay for all the others. No plan up to that building needs fewer bricks. The walk ends only when even that plan runs out of bricks.
Solution Approach
Turning that idea into code means first seeing why simpler plans fall short, then settling three things: where the climbs on ladders are kept, when one of them moves to bricks, and when the walk stops.
Simpler plans and why they fall short
Why not pay with bricks while they last, and bring out the ladders after that? Call that plan bricks first. It spends bricks on whatever climb comes first, even a big one. Take heights 0, 5, 6, 7 with 5 bricks and 1 ladder. Bricks first pays all 5 bricks for the climb of 5, puts the ladder on the first climb of 1, and is stuck at building 2.
Putting the ladder on the climb of 5 instead pays the two climbs of 1 with 2 bricks and reaches building 3. Trying every way to hand out the ladders would also find that plan, but with 20 climbs and 10 ladders there are already 184,756 ways to choose.
Keeping the climbs on ladders
Which climb should leave the list when it grows too long? Always the smallest. Looking through the whole list for it costs one step per ladder, and that can happen at every climb. A min-heap is built for this job: numbers can be added in any order, and the smallest is always at the front, ready to be taken out. With k numbers inside, adding one or taking the smallest out takes about log k steps. So the climbs on ladders are kept in a min-heap.
In Java, PriorityQueueComparator.naturalOrder()Comparator.reverseOrder()
Moving a climb to bricks
When does a climb leave the heap? Each new climb goes in first. If the heap now holds more climbs than there are ladders, the smallest is taken out with poll()
When the walk stops
What if the bricks are not enough? After paying, a negative number of bricks means the next move cannot be made by any plan, because the heap already holds the biggest climbs so far. So the building you are standing on is the answer. If the walk gets past the last climb, every building is reachable, and the answer is the last index.
Java Solution
The method furthestBuilding
- First, create the min-heap
withladderClimbs , so the smallest climb on a ladder is always on top.new PriorityQueue<>(Comparator.naturalOrder()) - Walk along the street with one loop. The loop moves
from building 0 to the second-to-last building and works outi , the rise from buildingclimb = heights[i + 1] - heights[i] to the next one. Ai of 0 or less is a step down or across, so the loop skips it.climb - Add every real climb to
, giving it a ladder for now.ladderClimbs - If
now holds more climbs thanladderClimbs , take the smallest out withladders and subtract it frompoll() .bricks - If
has dropped below 0, returnbricks , because the move to buildingi cannot be paid for.i + 1 - If the loop finishes, every building was reached, so return
.heights.length - 1
The main
import java.util.Comparator;
import java.util.PriorityQueue;
public class FarthestBuildingYouCanReachHeap {
public static int furthestBuilding(int[] heights, int bricks, int ladders) {
// min-heap: the smallest climb that is on a ladder sits on top
PriorityQueue<Integer> ladderClimbs = new PriorityQueue<>(Comparator.naturalOrder());
for (int i = 0; i + 1 < heights.length; i++) {
int climb = heights[i + 1] - heights[i];
if (climb <= 0) {
continue; // going down or level is free
}
ladderClimbs.add(climb); // give this climb a ladder for now
if (ladderClimbs.size() > ladders) {
bricks -= ladderClimbs.poll(); // a ladder short: pay the smallest in bricks
if (bricks < 0) {
return i; // cannot pay: building i is the farthest
}
}
}
return heights.length - 1;
}
public static void main(String[] args) {
System.out.println(furthestBuilding(new int[] {4, 2, 7, 6, 9, 14, 12}, 5, 1));
System.out.println(furthestBuilding(new int[] {4, 12, 2, 7, 3, 18, 20, 3, 19}, 10, 2));
System.out.println(furthestBuilding(new int[] {0, 5, 6, 7}, 5, 1));
System.out.println(furthestBuilding(new int[] {1, 5, 1, 2}, 3, 0));
System.out.println(furthestBuilding(new int[] {9, 5, 1}, 0, 0));
System.out.println(furthestBuilding(new int[] {7}, 0, 0));
}
}
Running it prints:
4
7
3
0
2
0
The answers 4 and 7 match the examples. In Example 2, the walk reaches building 7 with 3 bricks left and the climbs 8 and 15 on the two ladders. The climb of 16 to building 8 pushes the 8 out of the heap, and 3 bricks cannot pay for a climb of 8.
The 3 on the third line comes from heights 0, 5, 6, 7: the heap keeps the climb of 5 on the ladder and pays the two climbs of 1 with bricks. Bricks first stops at building 2 on the same street.
The 0 on the fourth line is the street with no ladders. Its first climb, 4, goes into the heap and straight back out, and 3 bricks cannot pay for it. The last two lines need nothing at all: the street 9, 5, 1 only goes down, so building 2 is reached, and a single building is already its own farthest building, index 0.
Complexity
The work is one walk along the n buildings, with at most two heap operations at each climb. Below, L is the number of ladders.
- Time: O(n log L), because the loop visits each of the n - 1 gaps once, and a climb costs one
and at most oneadd on a heap of at most L + 1 climbs.poll - Space: O(min(n, L)), because climbs paid with bricks leave the heap at once, so it never holds more than L + 1 climbs, nor more than the number of climbs on the street.
Taking back an earlier choice with the help of a heap, once a better one shows up, also solves