Furthest Building You Can Reach

You are given an integer array `heights` representing the heights of buildings, some `bricks`, and some `ladders`. You start at building `0` and move to the next building, possibly using bricks or ladders. When moving from building `i` to building `i + 1` (0-indexed): - 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*.

30:00

Furthest Building You Can Reach
medium
Free written solution
Topics
Companies

You are given an integer array heights representing the heights of buildings, some bricks, and some ladders.

You start at building 0 and move to the next building, possibly using bricks or ladders. When moving from building i to building i + 1 (0-indexed):

  • 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.

Example 1:
Input: {"heights":[4,2,7,6,9,14,12],"bricks":5,"ladders":1}
Output: 4
Constraints:
  • 1≤heights.length≤1051 \leq \text{heights.length} \leq 10^5

  • 1≤heights[i]≤1061 \leq \text{heights}[i] \leq 10^6

  • 0≤bricks≤1090 \leq \text{bricks} \leq 10^9

  • 0≤ladders≤heights.length0 \leq \text{ladders} \leq \text{heights.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"heights":[4,2,7,6,9,14,12],"bricks":5,"ladders":1}

7 buildings, 5 bricks, 1 ladder. A ladder covers any climb, so save ladders for the biggest climbs: keep the climbs on ladders in a min-heap and pay the smallest with bricks.

skyline; the label under a building says how you got onto it

4

2

7

6

9

14

12

0
1
2
3
4
5
6

ladders on the biggest climbs (min-heap, 0/1)

bricks left

5 / 5

you are here
L = climbed on a ladder
B = paid with bricks
Variables
VariableValue
i0
climb-
bricks5
ladders used0
DepthFunction Call
Stack empty
0/9