[LeetCode] Furthest Building You Can Reach

1642. Furthest Building You Can Reach

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int furthestBuilding(vector<int>& h, int b, int l) {
priority_queue<int, vector<int>, greater<int>> pq;
int res = 0;
for(int i = 0; i < h.size() - 1; i++) {
if(h[i] >= h[i+1]) continue;
pq.push(h[i+1] - h[i]);
if(pq.size() > l) {
if(pq.top() > b)
return i;
b -= pq.top();
pq.pop();
}
}
return h.size() - 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/furthest-building-you-can-reach/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.