Snowball Showdown

EasyheapAlso known as Last Stone Weight

A winter fair's snowball machine holds a pile of snowballs of different sizes. Each round, it fires the two biggest straight at each other.

Equal sizes both shatter. Otherwise the smaller one shatters and knocks that much snow off the bigger one, which drops back into the pile with its new size.

Your task

Write lastSnowball(sizes). Run rounds until fewer than two snowballs are left. Return the size of the one that remains, or 0 if none remain.

In a round where the two biggest have sizes a ≥ b: if a = b both disappear, otherwise a snowball of size a - b goes back into the pile.

lastSnowball(sizes: int[]) → int

Examples

Example 1
Input
sizes = [4, 9, 2, 6]
Output
1
Why

First 9 and 6 collide and a snowball of size 3 goes back, so the pile is [4, 2, 3]. Then 4 and 3 collide and a 1 goes back, leaving [2, 1]. Finally 2 and 1 collide and a 1 goes back, so one snowball of size 1 is left.

Example 2
Input
sizes = [5, 5, 3, 3]
Output
0
Why

5 and 5 shatter each other. Then 3 and 3 shatter each other. Nothing is left, so the answer is 0.

Example 3
Input
sizes = [7]
Output
7
Why

With only one snowball there is no round at all. The answer is 7.

Constraints

  • 1 ≤ sizes.length ≤ 100,000
  • 1 ≤ sizes[i] ≤ 1,000,000
Start with brute force

Sort the pile, take the two biggest from the end, put the difference back into the pile, and sort again.

Each sort is O(n log n) and there can be n rounds: O(n² log n), far beyond a billion steps for 100,000 snowballs. Inserting the leftover into a sorted array still costs O(n) per round for shifting, so O(n²) overall.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code