Last Stone Weight
It requires two major steps. In the first step, you need to find the two heaviest stones. In the second step, you smash these stones together according to the rules given. You repeat these steps until there is at most one stone left.
One efficient way to keep track of the two heaviest stones is to use a max heap, a type of priority queue. In Python, you can use the heapq library, which provides an implementation of heap queue algorithm (priority queue algorithm) using lists. However, heapq in Python implements a minheap, so we’ll store our stones as negative numbers to mimic a max heap.
Python solution:


In this code, we first create a max heap from the stones array. Then, in a loop, we pop two stones from the max heap, which will be the two heaviest stones because of the properties of the max heap. We then compare these two stones. If they are of equal weight, they both get destroyed. If they are not of equal weight, we push the difference back into the max heap. We repeat this process until there is one or no stone left. Finally, we return the weight of the last remaining stone if it exists, else we return 0. Note that because we’re working with a minheap representation of a maxheap, we multiply the result by 1 to convert it back to positive.