Last stone weight
Repeatedly smash the two heaviest stones together using a max-heap, until at most one stone remains.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
A max-heap always exposes the two heaviest stones at the front. Smash them together: the lighter one is destroyed, and the difference (if any) goes back on the heap as a new, usually lighter, stone. Repeat until at most one stone is left.
Code
public static int LastStoneWeight(int[] stones) {
var heap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b - a)); // max-heap
foreach (int s in stones) heap.Enqueue(s, s);
while (heap.Count > 1) {
int y = heap.Dequeue();
int x = heap.Dequeue();
if (y != x) heap.Enqueue(y - x, y - x);
}
return heap.Count == 1 ? heap.Peek() : 0;
}static int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder()); // max-heap
for (int s : stones) heap.offer(s);
while (heap.size() > 1) {
int y = heap.poll();
int x = heap.poll();
if (y != x) heap.offer(y - x);
}
return heap.size() == 1 ? heap.peek() : 0;
}int lastStoneWeight(const vector<int>& stones) {
priority_queue<int> heap; // max-heap
for (int s : stones) heap.push(s);
while (heap.size() > 1) {
int y = heap.top(); heap.pop();
int x = heap.top(); heap.pop();
if (y != x) heap.push(y - x);
}
return heap.size() == 1 ? heap.top() : 0;
}import heapq
def last_stone_weight(stones: list[int]) -> int:
heap = [] # max-heap (values stored negated)
for s in stones: heapq.heappush(heap, -s)
while len(heap) > 1:
y = -heapq.heappop(heap)
x = -heapq.heappop(heap)
if y != x: heapq.heappush(heap, -(y - x))
return -heap[0] if len(heap) == 1 else 0Tips
- Pushing the leftover stone back and letting the heap re-sort is simpler than tracking positions by hand.
- If the two heaviest stones are equal, both vanish — push nothing back.
In the .NET library
This greedy "always combine the two biggest" shape also shows up in Huffman coding, where you repeatedly merge the two least-frequent symbols instead of the two heaviest stones.