-
Notifications
You must be signed in to change notification settings - Fork 354
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #933 from Anirudh906/main
Add furthest_building_you_can_reach.cpp
- Loading branch information
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
/* | ||
Problem link: https://leetcode.com/problems/furthest-building-you-can-reach/ | ||
*/ | ||
|
||
class Solution | ||
{ | ||
public: | ||
int furthestBuilding(vector<int> &heights, int bricks, int ladders) | ||
{ | ||
int n = heights.size(); | ||
int i = 0; | ||
priority_queue<int, vector<int>, greater<int>> p; | ||
while (i < n - 1 and p.size() < ladders) | ||
{ | ||
int t = heights[i + 1] - heights[i]; | ||
if (t > 0) | ||
{ | ||
p.push(t); | ||
} | ||
i++; | ||
} | ||
while (i < n - 1) | ||
{ | ||
int t = heights[i + 1] - heights[i]; | ||
if (t > 0) | ||
{ | ||
if (t > p.top() and !p.empty()) | ||
{ | ||
bricks -= p.top(); | ||
p.pop(); | ||
p.push(t); | ||
} | ||
|
||
else | ||
{ | ||
bricks -= t; | ||
} | ||
} | ||
if (bricks < 0) | ||
return i; | ||
i++; | ||
} | ||
return i; | ||
} | ||
}; |