Input: heights =[4,2,7,6,9,14,12], bricks =5, ladders =1Output: 4Explanation: Starting at building 0, you can follow these steps:- Go to building 1 without using ladders nor bricks since 4>=2.- Go to building 2 using 5 bricks. You must use either bricks or ladders because 2<7.- Go to building 3 without using ladders nor bricks since 7>=6.- Go to building 4 using your only ladder. You must use either bricks or ladders because 6<9.It is impossible to go beyond building 4 because you do not have any more bricks or ladders.Example 2:
Ladders should be saved for the largest jumps since they can cover any height difference, making them more valuable. It’s best to use bricks first and only switch to ladders when bricks run out.
If bricks are used on a large jump, we can later swap that usage for a ladder to recover bricks for future steps.
Note that we are looping till n-2, because we are using index i+1 for heights array.
classSolution {
publicintfurthestBuilding(int[] heights, int bricks, int ladders) {
var pq =new PriorityQueue<Integer>(Collections.reverseOrder());
int bricksUsed = 0;
int n = heights.length;
for(int i = 0 ; i < n-1 ; i++){
int diff = heights[i+1]- heights[i];
// If current height is higher, we don't have to use// bricks or ladder.if(diff <= 0){
continue;
}
// We have to use either brick or ladder.if(diff + bricksUsed <= bricks){
// Prefer bricks because we can later change from // bricks to ladder as we will see below. bricksUsed += diff;
pq.add(diff);
} elseif(ladders > 0){
// If even bricks are insufficient, check ladders.// if peek of heap is more than current diff// then remove peek heap, and get back some bricks pq.offer(diff);
int maxUsedBricks = pq.peek();
bricksUsed += maxUsedBricks - diff;
ladders--;
}
// Unfortunately, it's not possible to go ahead any further.elsereturn i;
}
// This is the max we can go ahead.return n-1;
}
}
Let diff be the difference between consecutive building heights.
Instead of using a max-heap to reclaim bricks, we can use a min-heap to keep track of the largest k jumps where ladders are used.
For each positive diff, add it to the min-heap; if the heap size exceeds the number of ladders, use bricks for the smallest jump by removing it from the heap and subtracting from bricks.
If bricks run out (bricks < 0), return the current index; otherwise, if all buildings are reachable, return the last index.
classSolution {
public:int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
priority_queue<int, vector<int>, greater<int>> minHeap;
int n = heights.size();
for (int i =0; i < n -1; ++i) {
int diff = heights[i +1] - heights[i];
if (diff >0) {
minHeap.push(diff);
}
if (minHeap.size() > ladders) {
bricks -= minHeap.top();
minHeap.pop();
}
if (bricks <0) {
return i;
}
}
return n -1;
}
};