-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path1642. Furthest Building You Can Reach
51 lines (48 loc) · 1.48 KB
/
1642. Furthest Building You Can Reach
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i = 1; i < heights.length; i++) {
int diff = heights[i] - heights[i-1];
if(diff > 0) {
if(pq.size() < ladders) {
pq.offer(diff);
}
else {
int br = diff;
//Optimize previous ladder use
if(pq.size() > 0 && pq.peek() < diff) {
br = pq.remove();
pq.offer(diff);
}
if(bricks-br >= 0) {
bricks-=br;
}
else {
return i-1;
}
}
}
}
return heights.length-1;
}
}
class Solution {
public int furthestBuilding(int[] heights, int bricks, int ladders) {
int n=heights.length;
PriorityQueue<Integer> q= new PriorityQueue<>();
int brickesUsed=0;
for(int i=1;i<n;i++){
int diff= heights[i] - heights[i-1];
if(diff>0){
q.add(diff);
if(q.size()>ladders){
brickesUsed+=q.remove();
}
if(brickesUsed>bricks){
return i-1;
}
}
}
return n-1;
}
}