iq.lab
Python starts when a code cell comes near or you run one
easyHeaps target 15 min

Last stone weight

A pile of stones lies on a table, and the list stones holds their weights. A round goes like this: take the two heaviest stones off the pile and crash them into each other. If they weigh the same, both turn to dust. If not, the lighter one turns to dust and the heavier one loses as much weight as the lighter one had: stones of 7 and 3 leave one stone of 4, which goes back on the pile.

Keep playing rounds while two or more stones are on the pile. Then return the weight of the stone that is left, or 0 if the pile is empty. Leave the list stones itself unchanged.

Example 1
Inputstones = [4, 10, 3, 7]Output2

Smash 10 and 7: a 3 goes back, so the pile is 4, 3, 3. Smash 4 and 3: a 1 goes back, so the pile is 3, 1. Smash 3 and 1: a 2 is left alone.

Example 2
Inputstones = [5, 5]Output0

Equal stones destroy each other, so nothing is left.

Example 3
Inputstones = [9]Output9

One stone needs no round.

Constraints
  • 1 ≤ len(stones) ≤ 3 × 104

  • 1 ≤ stones[i] ≤ 105

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.