Last Stone Weight
Last Stone Weight
Problem Statement
You are given an array of integers stones
where stones[i]
is the weight of the i
th stone. We are playing a game with the stones. On each turn, we choose the two heaviest stones and smash them together. Suppose the heaviest two stones have weights x
and y
with x <= y
. The result of this smash is:
- If
x == y
, both stones are destroyed. - If
x != y
, the stone of weightx
is destroyed, and the stone of weighty
has new weighty - x
.
At the end of the game, there is at most one stone left. Return the weight of the last remaining stone. If there are no stones left, return 0.
Example
Input: stones = [2,7,4,1,8,1]
stones: [2, 7, 4, 1, 8, 1]
Output: 1
Output: 1
Solution
This problem can be solved efficiently using a max heap. We add all the stone weights to a max heap. Then, as long as there are more than one stone in the heap, we extract the two heaviest stones, smash them, and add the result back to the heap if it's not zero.
Algorithm Steps
- Create a max heap from the `stones` array.
- While the heap has more than one element:
- Pop the two largest stones.
- If they are not equal, push their difference back to the heap.
- If the heap is empty, return 0. Otherwise, return the last remaining stone.
Last Stone Weight
Max Heap Approach
Input: stones = [2, 7, 4, 1, 8, 1]
Output: 0
Ready to start the visualization
Max Heap