Last Stone Weight

Easy Heap / Priority Queue

stones holds the weights of a pile of stones.

Each turn, the two heaviest stones left are smashed together. If they weigh the same, both break; if not, the lighter one breaks and the heavier one stays, having lost as much weight as the lighter one had. The turns go on while at least two stones are left.

Return the weight of the stone left at the end, or 0 if none is left.

Example 1

Input: stones = [3,9,4,2]
Output: 0

9 and 4 leave a stone of 5. Then 5 and 3 leave 2, and the two stones of 2 break each other, so none is left.

Example 2

Input: stones = [10,4,4]
Output: 2

Example 3

Input: stones = [5,5,5]
Output: 5

Constraints

  • 1 ≤ stones.length ≤ 2 × 10⁵
  • 1 ≤ stones[i] ≤ 10⁹

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Heap / Priority Queue

All Heap / Priority Queue problems