Intermediate Level

Implement the lastStoneWeightHeap method that returns the final stone weight after repeatedly smashing the two heaviest stones.

The input array stones contains the weights of size stones.

Your task is to repeatedly smash the two heaviest stones together until at most one stone remains.

If both stones have the same weight, both are destroyed. If they have different weights, the remaining stone has weight equal to their difference. Return the final stone weight, or 0 if no stone remains.

Example 1
Input:
stones (int[]) = [2,7,4,1,8,1]
size (int) = 6
Return:
(int) 1
Example 2
Input:
stones (int[]) = [1]
size (int) = 1
Return:
(int) 1
Example 3
Input:
stones (int[]) = [10,4,2,10]
size (int) = 4
Return:
(int) 2

Use a max heap so the two heaviest stones can be removed quickly.

In every round, remove the largest and second largest stones. If they are equal, do not insert anything back. If they are different, insert the difference back into the heap.

When the heap becomes empty, return 0. Otherwise, return the only remaining stone.

Pseudocode:

function lastStoneWeightHeap(stones, size):
    create maxHeap from stones
    while heap size > 1:
        first = remove largest from maxHeap
        second = remove largest from maxHeap
        if first != second:
            push first - second into maxHeap
    if heap is empty:
        return 0
    return top of maxHeap
Run your code to see the result.