# 1046. Last Stone Weight

We have a collection of stones, each stone has a positive integer weight.

Each turn, we choose the two heaviest stones and smash them together.  Suppose the stones have weights `x` and `y` with `x <= y`.  The result of this smash is:

• If `x == y`, both stones are totally destroyed;
• If `x != y`, the stone of weight `x` is totally destroyed, and the stone of weight `y` has new weight `y-x`.

At the end, there is at most 1 stone left.  Return the weight of this stone (or 0 if there are no stones left.)

Example 1:

``````Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone.
``````

Note:

1. `1 <= stones.length <= 30`
2. `1 <= stones[i] <= 1000`

``````class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> q;
for (int stone : stones) q.push(stone);
while (q.size() > 1) {
int first = q.top(); q.pop();
int second = q.top(); q.pop();
if (first > second) q.push(first - second);
}
return q.empty() ? 0 : q.top();
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1046

https://leetcode.com/problems/last-stone-weight/

https://leetcode.com/problems/last-stone-weight/discuss/294956/JavaC%2B%2BPython-Priority-Queue

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation