# 1642. Furthest Building You Can Reach

## Understanding the Problem:

Imagine traversing a series of buildings, each with its own height. We’re equipped with a limited supply of bricks and ladders, and our goal is to reach as far as possible while conserving resources. The furthest building problem challenges us to determine the maximum distance we can travel given the heights of the buildings, the number of bricks available, and the number of ladders we can use.

## The Solution Approach:

Our Java solution employs a clever combination of priority queues and iterative traversal to navigate the landscape of buildings. Let’s break down the key components of the code:

1. PriorityQueue for Ladders: We start by initializing a PriorityQueue to store the differences in height between adjacent buildings. This PriorityQueue acts as a pool of ladders, prioritizing the tallest height differences.
2. Iterative Traversal: We iterate through the array of building heights, comparing each building’s height with the previous one. If the current building is taller than the previous one, we calculate the height difference.
3. Managing Resources:
• If the PriorityQueue has fewer ladders than the maximum allowed, we simply add the height difference to the PriorityQueue.
• If the PriorityQueue is full, we compare the height difference with the smallest value in the PriorityQueue. If the difference is greater, we replace the smallest difference with the current one.
4. Checking Resource Limits: At each step, we check if the total height difference exceeds the available bricks. If it does, we return the index of the previous building, indicating the furthest distance we can travel with the current resources.
5. Returning the Furthest Distance: If we successfully traverse the entire array without exhausting the brick supply, we return the index of the last building, indicating that we’ve reached the furthest distance possible.
``````class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
int count = 0;
for(int i=1;i<heights.length;i++)
{
if(heights[i] <= heights[i-1])
{
continue;
}
int diff = heights[i] - heights[i-1];
{
}
{
if(ladders != 0 && queue.peek() < diff)
{
count += queue.poll();
}
else
{
count += diff;
}
}
if(count > bricks)
{
return i-1;
}

}
return heights.length-1;
}
}
``````

https://leetcode.com/problems/furthest-building-you-can-reach/?envType=daily-question&envId=2024-02-17