Furthest Building You Can Reach

Medium

Description

You are given an integer array heights representing building heights. You have some bricks and ladders. A ladder lets you climb any height difference, bricks must cover the exact difference. Return the index of the furthest building you can reach.

Examples

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

Can reach building 4 using resources.

Input:heights = [1,5,1,2,3,4,10,4,6,7,3,4], bricks = 4, ladders = 1
Output:6
Explanation:

Starting at building 0: climb from 1→5 (use 4 bricks), drop to 1→2→3→4, climb from 4→10 (use 1 ladder). Reaching building 6 (height 10). Next climb would be 4→6 needing 2 bricks, but there are 0 bricks and 0 ladders left.

Input:heights = [10,8,6,4,2], bricks = 100, ladders = 0
Output:4
Explanation:

All buildings are decreasing in height (10→8→6→4→2), so there is never a need to need to climb up. It is possible to reach the last building at index 4 without using any bricks or ladders since only go downward.

Constraints

  • 1 ≤ heights.length ≤ 10^5
  • 1 ≤ heights[i] ≤ 10^6

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!