AlgoInsight

DSA problem

Furthest Building You Can Reach

MediumHeapsPattern: Heapstop150FreeAmazonMicrosoftGoogleMetaApple

You are given an integer array heights representing the heights of buildings, some bricks, and some ladders. You start your journey from building 0 and move to the next building by possibly using bricks or ladders.

While moving from building i to building i + 1: if the current building's height is greater than or equal to the next building's height, you do not need a ladder or bricks. If the current building's height is less than the next building's height, you can either use one ladder OR (h[i+1] - h[i]) bricks. Return the furthest building index (0-indexed) you can reach if you use the given ladders and bricks optimally.

The greedy insight is that ladders are the most powerful resource — each one covers an arbitrarily large gap. So we should save ladders for the biggest gaps we encounter and pay for the smaller gaps with bricks. But we cannot know in advance which gaps are "big" until we have walked the whole street.

Use a min-heap of the gaps where a ladder is currently allocated. For every positive gap we encounter, push it onto the heap. Whenever the heap holds more than ladders entries, the smallest of those gaps is no longer worth a ladder — pop it and pay for that gap with bricks instead. If bricks ever go negative, we cannot reach the next building, so return the previous index. Otherwise we walk all the way to the last building. The total work is O(n log L) where L is the number of ladders.

Examples

Example 1
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation: Use 0 bricks/ladders to step from 4 to 2 (going down). Use 5 bricks to step from 2 to 7 (gap of 5). Use 0 to step from 7 to 6. Use the ladder to step from 6 to 9 (gap 3). Now at index 4, no bricks/ladders left → cannot proceed.
Example 2
Input: heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2
Output: 7
Explanation: Use a ladder for the big jump 4 → 12. Use bricks for smaller jumps. Save the second ladder for 7 → 18 or 18 → 20. Optimal play reaches building index 7.
Example 3
Input: heights = [14,3,19,3], bricks = 17, ladders = 0
Output: 3
Explanation: No ladders are available. Only one positive gap (3 → 19) requires 16 bricks, which we can afford, so we reach the last building.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

heappriority-queuegreedyarray

Browse all DSA problems