Last Stone Weight

Heaps & Top-K, problem 1 of 7

Last Stone Weight

Easy

LC #1046

max-heapsimulation

Not attempted yet

You have a pile of stones with positive integer weights. Each turn, pick the two heaviest stones, x <= y, and smash them:

  • if x == y, both are destroyed
  • otherwise x is destroyed and y becomes y - x

Repeat until at most one stone is left. Return its weight, or 0 if none remain.

Example 1

Input: stones = [2,7,4,1,8,1]
Output: 1

8 and 7 → 1; 4 and 2 → 2; 2 and 1 → 1; 1 and 1 → gone; one stone of weight 1 is left.

Example 2

Input: stones = [1]
Output: 1

Example 3

Input: stones = [3,7,2]
Output: 2

7 and 3 → 4; 4 and 2 → 2.

Constraints

  • 1 <= len(stones) <= 3 * 10^4
  • 1 <= stones[i] <= 1000

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.