From 0e4c4ab2c7e89f650f9495fa5ef4cd6fede5059e Mon Sep 17 00:00:00 2001 From: ahmedgamal2212 Date: Mon, 24 Apr 2023 09:18:03 +0200 Subject: [PATCH] Add solution to day 24 --- .../24- Last Stone Weight (Ahmed Gamal).cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 04- April/24- Last Stone Weight/24- Last Stone Weight (Ahmed Gamal).cpp diff --git a/04- April/24- Last Stone Weight/24- Last Stone Weight (Ahmed Gamal).cpp b/04- April/24- Last Stone Weight/24- Last Stone Weight (Ahmed Gamal).cpp new file mode 100644 index 000000000..5e590d0f2 --- /dev/null +++ b/04- April/24- Last Stone Weight/24- Last Stone Weight (Ahmed Gamal).cpp @@ -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& stones) { + // initialize the priority queue + priority_queue 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(); + } +}; \ No newline at end of file