Skip to content

Commit a00e692

Browse files
Create 1642-furthest-building-you-can-reach.java
1 parent 5ab295f commit a00e692

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/* Max Heap Method
2+
----------------------------------------*/
3+
class Solution {
4+
public int furthestBuilding(int[] heights, int bricks, int ladders) {
5+
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
6+
for (int i = 0; i < heights.length - 1; i++) {
7+
int diff = heights[i + 1] - heights[i];
8+
9+
if (diff <= 0)
10+
continue;
11+
12+
bricks -= diff;
13+
pq.add(diff);
14+
15+
if(bricks < 0){
16+
if(ladders == 0)
17+
return i;
18+
ladders -= 1;
19+
bricks += pq.poll();
20+
}
21+
}
22+
return heights.length - 1;
23+
}
24+
}
25+
26+
/* Min Heap Method
27+
-----------------------------------------------*/
28+
class Solution {
29+
public int furthestBuilding(int[] heights, int bricks, int ladders) {
30+
PriorityQueue<Integer> pq = new PriorityQueue<>();
31+
for(int i = 0; i < heights.length-1; i++){
32+
int diff = heights[i + 1] - heights[i];
33+
if(diff < 0)
34+
continue;
35+
pq.add(diff);
36+
if(pq.size() > ladders)
37+
bricks -= pq.poll();
38+
if(bricks < 0)
39+
return i;
40+
}
41+
return heights.length - 1;
42+
}
43+
}

0 commit comments

Comments
 (0)