LeetCode 1642: Furthest Building You Can Reach

Problem Description

Explanation:

To solve this problem, we can use a priority queue to store the height differences between buildings. We iterate through the buildings, calculating the height difference between each pair of consecutive buildings. If the height difference is positive, meaning we need a ladder to climb, we push this height difference into the priority queue. If the queue size exceeds the number of available ladders, we use bricks to replace the smallest height difference in the queue. We continue this process until we reach the end of the buildings or run out of bricks and ladders. The furthest building index we can reach will be the current index at the end of the iteration.

Algorithm:

  1. Initialize a priority queue to store the height differences.
  2. Iterate through the buildings while keeping track of the current index.
  3. Calculate the height difference between each pair of consecutive buildings.
  4. If the height difference is positive, push it into the priority queue.
  5. If the queue size exceeds the number of ladders, replace the smallest height difference with bricks.
  6. Continue this process until reaching the end of the buildings or running out of bricks and ladders.
  7. Return the current index as the furthest building index.

Time Complexity: O(n log k), where n is the number of buildings and k is the number of ladders.

Space Complexity: O(k), where k is the number of ladders.

:

Solutions

class Solution {
    public int furthestBuilding(int[] heights, int bricks, int ladders) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        int n = heights.length;
        
        for (int i = 0; i < n - 1; i++) {
            int diff = heights[i+1] - heights[i];
            if (diff > 0) {
                pq.offer(diff);
                if (pq.size() > ladders) {
                    bricks -= pq.poll();
                    if (bricks < 0) return i;
                }
            }
        }
        
        return n - 1;
    }
}

Loading editor...