题目
You are given an integer array heights representing the heights of buildings,
some bricks, and some ladders.You start your journey from building 0 and move to
the next building by possibly using bricks or ladders.While moving from building
i to building i+1 (0-indexed), If the current building's height is greater than
or equal to the next building's height, you do not need a ladder or bricks. If the
current building's height is less than the next building's height, you can either
use one ladder or (h[i+1] - h[i]) bricks. Return the furthest building index (0-indexed)
you can reach if you use the given ladders and bricks optimally.
Input: heights = [4,2,7,6,9,14,12], bricks = 5, ladders = 1
Output: 4
Explanation: 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.
题目翻译过来,意思是:
给你一个整数数组heights,表示建筑物的高度,另有一些砖块和梯子。你从建筑物0开始出发,不断向后面的建筑物移动,当从建筑物i移动到建筑物i+1时:
- 如果当前建筑物的高度大于或等于下一建筑物的高度,则不需要梯子或砖块
- 如果当前建筑的高度小于下一个建筑的高度,我们可以使用一架梯子或 (h[i+1] - h[i]) 个砖块,来帮助我们到达下一个建筑物
找出最佳方式使用给定的梯子和砖块的方法,使你可以到达最远的建筑,返回你可以到达的最远建筑物的下标(下标 从 0 开始 )。
题目分析
分析题意,我们知道对于每一个位置i来说,如果他的下一个位置i + 1的高度比自己要矮,那么我们不需要消耗梯子或者砖头;反之如果他的下一个位置高度比自己要高,我们就需要消耗梯子或者砖头。那么我们到底是该使用梯子还是砖头呢,从题目中我们知道梯子的高度是任意的,但是砖头的数量是有限的,所以这里我们采用贪心的思想,先用梯子,当梯子用完之后,我们看看用过梯子的地方是否有可能被砖头替换掉,而这里为了尽可能节省砖头,所以我们应该选择使用砖头数目最少的那个建筑物来用砖头替换梯子,这样我们就可以利用省下的梯子再去走更远的距离。
所以为了在梯子不够用时候找到使用最少砖头的建筑物,我们使用最小堆来记录建筑物的diff值(也就是如果用砖头,使用的砖头数目),高度差最小的在堆顶,这样当梯子用完的时候,我们可以优先去用砖头替换高度差较小的,这样可以尽可能地把砖头利用完。
代码实现
// 时间O(nlogn); 空间O(n)
public class T1642FurthestBuildingYouCanReach {
public static void main(String[] args) {
Solution solution = new T1642FurthestBuildingYouCanReach().new Solution();
// write test case
int[] height = {4,2,7,6,9,14,12};
int bricks = 5;
int ladders = 1;
System.out.println(solution.furthestBuilding(height, bricks, ladders));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
// 优先级队列存储建筑物高度差(只有h[i] - h[i-1] > 0时候才存储)
PriorityQueue<Integer> q = new PriorityQueue<>();
for (int i = 1; i < heights.length; ++i) {
int diff = heights[i] - heights[i-1];
if (diff > 0) {
q.add(diff);
}
if (q.size() > ladders) {
bricks -= q.poll();
}
if (bricks < 0) {
return i - 1;
}
}
return heights.length - 1;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}