Skip to main content
Back to problems
Leetcode
Medium
Arrays
Heaps
Greedy
Google
Furthest Building You Can Reach

Use a limited number of bricks and ladders to climb a sequence of buildings and return the farthest index you can reach.

Acceptance 50%
Problem Statement

You are given an array of building heights in left-to-right order, along with a number of bricks and ladders.

You start at building index 0. To move from building i to i + 1:

  • If the next building is not taller, no resources are needed.
  • If the next building is taller by d, you must cover that climb using either d bricks or one ladder.

Bricks are consumed exactly by the height difference, while a ladder can cover any single positive climb regardless of size.

Your task is to determine the furthest building index you can reach by spending the resources optimally.

Input Format

  • heights: an array of integers representing building heights from left to right.
  • bricks: the total number of bricks available.
  • ladders: the total number of ladders available.

Output Format

Return the largest index of a building that can be reached starting from index 0.

Constraints

  • 1 <= heights.length
  • heights[i] are integers.
  • bricks >= 0
  • ladders >= 0
  • You may choose independently whether to use bricks or a ladder on each positive climb.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

4

Explanation

Climb 2 -> 7 uses the ladder or bricks. The optimal strategy is to reserve the ladder for a larger climb later, so the farthest reachable building is index 4 (height 9).

Example 2

Input

heights = [4,12,2,7,3,18,20,3,19], bricks = 10, ladders = 2

Output

7

Explanation

Use ladders on the largest climbs and bricks on the smaller ones. With optimal allocation, you can reach index 7.

Show 1 more example

Example 3

Input

heights = [14,3,19,3], bricks = 17, ladders = 0

Output

3

Explanation

The positive climbs are 3 -> 19, which costs 16 bricks. That is within the budget, so the last building is reachable.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.