Skip to content

Commit

Permalink
Merge pull request #933 from Anirudh906/main
Browse files Browse the repository at this point in the history
Add furthest_building_you_can_reach.cpp
  • Loading branch information
noisefilter19 authored Oct 2, 2021
2 parents 769a326 + eaf4e87 commit 91afdb1
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions C++/Furthest_building_you_can_reach.cpp
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;
}
};

0 comments on commit 91afdb1

Please sign in to comment.