Practice · Heap · 2 of 5

Smash the Heaviest Stones

You have a pile of stones, and stones[i] is the weight of one of them. Each turn, take the two heaviest stones, weighing x and y with x ≤ y, and smash them together:

  • If x == y, both stones are destroyed.
  • Otherwise the lighter stone is destroyed and the heavier one now weighs y − x. It goes back in the pile.

Keep going until at most one stone is left. Return its weight, or 0 if no stone is left.

Example 1

Input
stones = [6, 3, 10, 2]
Output
1
Smash 10 and 6 (a 4 is left), then 4 and 3 (a 1 is left), then 2 and 1: one stone weighing 1 remains.

Example 2

Input
stones = [3, 9, 4, 2, 8]
Output
0
9 and 8 leave a 1, 4 and 3 leave a 1, 2 and 1 leave a 1, and the last two stones weigh 1 each, so they destroy each other.

Constraints

  • stones holds 1 to 1000 weights.
  • Every weight is between 1 and 1000.
Brush up firstHeap visualiser