Skip to content
BytePatterns

Smash Heaviest Stones

EasyHeaps#max-heap#simulation~20m

Problem

A pile of stones is described by their weights. Repeatedly take the two heaviest stones and smash them together: equal stones destroy each other completely, while unequal ones leave a single stone weighing the difference, which goes back into the pile. Return the weight of the last stone left, or 0 when the pile empties.

Examples

Input:  stones = [2, 7, 4, 1, 8, 1]
Output: 1
Why:    7 and 8 leave 1, then 2 and 4 leave 2, then 1 and 2 leave 1, then 1 and 1 vanish
Input:  stones = [1, 1]
Output: 0
Why:    two equal stones destroy each other and nothing remains
Input:  stones = [3]
Output: 3
Why:    edge case, a lone stone has nothing to smash against

Hints

0 / 3

Stuck on the idea rather than the code? Heap Basics covers it.