Leetcode 1642: Furthest Building You Can Reach

grid47
grid47
Exploring patterns and algorithms
May 26, 2024 7 min read

You are given an array heights representing the heights of buildings, along with a certain number of bricks and ladders. Your task is to determine the furthest building you can reach by optimally using bricks and ladders.
Problem
Approach
Steps
Complexity
Input: You are given an array `heights` of length `n`, where each element represents the height of a building. You are also given two integers: `bricks` (the number of bricks available) and `ladders` (the number of ladders available).
Example: heights = [7, 12, 6, 9, 5, 17, 21, 4, 18], bricks = 15, ladders = 3
Constraints:
• 1 <= heights.length <= 10^5
• 1 <= heights[i] <= 10^6
• 0 <= bricks <= 10^9
• 0 <= ladders <= heights.length
Output: Return the furthest building index (0-indexed) you can reach using the given ladders and bricks optimally.
Example: 4
Constraints:
• Return -1 if you cannot move beyond the first building.
Goal: To move from building to building, using bricks and ladders optimally for the height differences.
Steps:
• 1. Calculate the height difference between each consecutive building.
• 2. Use ladders for the largest height differences first.
• 3. Use bricks for the remaining height differences.
• 4. Stop when you run out of bricks or ladders, and return the furthest building index.
Goal: Ensure you handle up to the maximum constraints efficiently.
Steps:
• The input array can have up to 100,000 elements.
• The number of bricks and ladders can be large, so optimize for performance.
Assumptions:
• Assume the height array is non-empty.
• Assume the number of ladders is non-negative and within the bounds of the array length.
Input: heights = [5, 3, 8, 7, 10, 15, 13], bricks = 8, ladders = 2
Explanation: You can move from building 0 to building 4 by optimally using bricks for the height difference between buildings 1 and 2 and using a ladder for the difference between buildings 3 and 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus