Furthest Building You Can Reach

Medium Topics Company Tags

Start at index 0 of the building-height array heights and move forward one building at a time. Moving to an equal or lower building costs nothing. To move to a taller building, either spend bricks equal to the height increase or use one ladder, which covers any increase. Given bricks and ladders, return the largest zero-based index you can reach by choosing how to spend them optimally.

Example 1:

Furthest Building You Can Reach, example 1: illustration of the example

Input: heights = [2,5,4,10]
bricks = 3
ladders = 1

Output: 3

Explanation: Spend 3 bricks on the climb from 2 to 5. Moving down to 4 is free. Use the ladder on the climb from 4 to 10 and reach the last building, at index 3.

Example 2:

Furthest Building You Can Reach, example 2: illustration of the example

Input: heights = [1,4,8]
bricks = 3
ladders = 0

Output: 1

Explanation: The first climb uses all 3 bricks. The next climb needs 4 bricks or a ladder, and neither is available, so the furthest reachable index is 1.

Example 3:

Furthest Building You Can Reach, example 3: illustration of the example

Input: heights = [9,7,7,2]
bricks = 0
ladders = 0

Output: 3

Explanation: Every move is downward or stays at the same height. No bricks or ladders are needed, and the last index is 3.

Constraints:

  • 1 <= heights.length <= 100000
  • 1 <= heights[i] <= 1000000
  • 0 <= bricks <= 1000000000
  • 0 <= ladders <= heights.length


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.