Snowball Showdown

EasyheapAlso known as Last Stone Weight

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

If they are the same size, both shatter. If not, the smaller one shatters and knocks that much snow off the bigger one, which drops back into the pile with its new size. The crowd bets on what is left when fewer than two snowballs remain.

Your task

Write lastSnowball(sizes). Run the rounds described above 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

9 and 6 collide: 3 goes back, pile [4, 2, 3]. 4 and 3 collide: 1 goes back, pile [2, 1]. 2 and 1 collide: 1 goes back. 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, and sort again. Repeat.

Each sort costs O(n log n), and there can be up to n rounds, so the total is O(n² log n). With 100,000 snowballs that is far beyond a billion steps. Even inserting the leftover into a sorted array in the right place costs O(n) per round because of 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