forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f7b5466
commit 0e4c4ab
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
04- April/24- Last Stone Weight/24- Last Stone Weight (Ahmed Gamal).cpp
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,40 @@ | ||
// Author: Ahmed Gamal | ||
|
||
// for this problem, we need to find the last stone after all the operations | ||
// we can use a priority queue to solve it (max heap) | ||
// at first, we push all the stones into the priority queue | ||
// then, we try to get the two heaviest stones and break them | ||
// if the two stones are equal, then we don't need to push anything into the priority queue | ||
// otherwise, we need to push the difference between the two stones into the priority queu | ||
|
||
class Solution { | ||
public: | ||
int lastStoneWeight(vector<int>& stones) { | ||
// initialize the priority queue | ||
priority_queue<int> pq; | ||
for(auto& i : stones) { | ||
pq.push(i); | ||
} | ||
|
||
// get the top element from the priority queue | ||
auto get = [&]() -> int { | ||
int x = pq.top(); | ||
pq.pop(); | ||
return x; | ||
}; | ||
|
||
// try to get the two heaviest stones and break them | ||
while(pq.size() > 1) { | ||
int y = get(); | ||
int x = get(); | ||
|
||
// if the two stones are equal, then we don't need to push anything into the priority queue | ||
if(y - x) { | ||
pq.push(y - x); | ||
} | ||
} | ||
|
||
// return the answer | ||
return pq.empty() ? 0 : pq.top(); | ||
} | ||
}; |