Last Stone Weight: the idea to remember.
Repeatedly smash the two heaviest stones, keeping their positive difference, until at most one remains.
The core insight
Extract the two greatest weights from a max heap and insert their difference when unequal.
Why it works
The heap always exposes the next required pair, and each smash reduces the number of stones.
The mistake to avoid
Equal stones disappear together; an empty heap means result zero.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
// Java reference adapted from neetcode-gh/leetcode (MIT).
// Extract the two greatest weights from a max heap and insert their difference when unequal.
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> maxHeap = new PriorityQueue();
for (int stone : stones) maxHeap.add(-stone);
while (maxHeap.size() > 1) {
int stone1 = maxHeap.remove();
int stone2 = maxHeap.remove();
if (stone1 != stone2) maxHeap.add(stone1 - stone2);
}
return maxHeap.size() != 0 ? (-maxHeap.remove()) : 0;
}Java reference adapted from neetcode-gh/leetcode · MIT license
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.