Binary Min / Max Heap

Last Stone Weight

Easy
Solve it on LeetCode ↗

The problem

Repeatedly smash the two heaviest stones together: equal stones vanish, unequal leaves their difference. Return the final stone’s weight, or 0.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Build a max-heap from the stones.
  2. 2While at least two stones remain: pop the top two; if they differ, push the difference.
  3. 3Return the last stone or 0.

Key insight

The simulation is forced — no greedy shortcut exists — so the entire problem is choosing the structure that makes "extract max twice" cheap.

The solution

Watch out for

  • Remember to negate BOTH on push and pop with the negation trick.
  • Sorting each round instead of using a heap is O(n² log n) — noticeable at scale.