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.
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