Skip to content

Commit e8e0a19

Browse files
Create furthest_building_reach_possible.cpp
1 parent e9ecdfd commit e8e0a19

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

furthest_building_reach_possible.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class Solution {
2+
public:
3+
int furthestBuilding(vector<int>& heights, int bricks, int ladders) {
4+
5+
/*
6+
The idea is :-
7+
8+
- Ladder allows infinite jumps and bricks have h[i+1] - h[i] possible jumps at given i.
9+
We have to use ladder juidiciously.
10+
11+
- This means, greddily picking up bricks and ensuring that we run out of bricks first. then if ladders are remaining, use them.
12+
13+
- Also, we have to find the place where we used maximum number of bricks and change it to ladder so that we can regain those many bricks that can be used ahead. => For this purpose we use a maxHeap to maintain the count of bricks used.
14+
15+
*/
16+
17+
if(heights.size() == 0) return 0;
18+
19+
priority_queue<int> bricksUsed; //maxHeap;
20+
21+
for(int i = 0; i < heights.size() - 1; ++i) {
22+
23+
if(heights[i] >= heights[i+1]) continue; //prev >= next
24+
25+
int difference = heights[i+1] - heights[i];
26+
bricksUsed.push(difference);
27+
bricks -= difference;
28+
29+
if(bricks >= 0) continue; //more usage of bricks possible
30+
31+
if(ladders == 0) return i; //if we are out of ladders, that's the furthest we can reach
32+
33+
bricks += bricksUsed.top(); //pick the most used bricks(most difference) and then replace it with ladder; thereby regaining the bricks
34+
bricksUsed.pop();
35+
ladders--;
36+
}
37+
38+
return heights.size() - 1;
39+
40+
}
41+
};

0 commit comments

Comments
 (0)