The problem. You have a pile of stones with weights stones[i]. Each turn, take the two heaviest stones, x ≤ y, and smash them together. If x == y, both are destroyed. Otherwise the lighter one is destroyed and the heavier one's weight becomes y − x. When at most one stone is left, return its weight — or 0 if none is left.
stones = [2, 7, 4, 1, 8, 1] -> 1
stones = [1] -> 1
stones = [3, 3] -> 0 (both destroyed)
stones = [10, 4, 2, 10] -> 2 (10 and 10 vanish, then 4 - 2)Every turn asks the same question — *which two stones are heaviest now?* — and every turn may add a new stone. That's the heap signal: repeatedly take the largest, while values are still being added.
Free account
Sign up to read the rest of this lesson: 6 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come