Algo-Sim › Heaps & Priority Queues
Last Stone Weight
Easy · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input
Repeatedly smash the two heaviest stones: a max-heap hands them out in O(log n) each.
Problem
You have stones with positive integer weights. Each turn, take the two heaviest, y ≥ x. If x == y both are destroyed; otherwise x is destroyed and y becomes y − x. Return the weight of the last stone, or 0 if none is left.
Constraints
- 1 ≤ stones.length ≤ 30
- 1 ≤ stones[i] ≤ 1000
Edge cases to test
- One stone
- Two equal stones (both vanish):
0 - All stones equal
Follow-up questions
- What if you may choose the pairs freely?
- Then it is a partition problem: split into two piles as equal as possible (subset-sum DP, LC 1049).
- How does Python make a max-heap?
- Push negated values into
heapq, which is a min-heap.
Solution
Java
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> heap = new PriorityQueue<>(Collections.reverseOrder());
for (int s : stones) heap.offer(s);
while (heap.size() > 1) {
int y = heap.poll();
int x = heap.poll();
if (x != y) heap.offer(y - x);
}
return heap.isEmpty() ? 0 : heap.peek();
}Python
import heapq
def last_stone_weight(stones):
heap = [] # weights negated: heapq is a min-heap
for s in stones:
heapq.heappush(heap, -s)
while len(heap) > 1:
y = -heapq.heappop(heap)
x = -heapq.heappop(heap)
if x != y:
heapq.heappush(heap, -(y - x))
return -heap[0] if heap else 0C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lastStoneWeight(vector<int> &stones) {
priority_queue<int> heap;
for (int s : stones)
heap.push(s);
while (int(heap.size()) > 1) {
int y = heap.top();
heap.pop();
int x = heap.top();
heap.pop();
if (x != y)
heap.push(y - x);
}
return heap.empty() ? 0 : heap.top();
}
};
More Heaps & Priority Queues problems
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- Reorganize String (Medium)
- IPO (Hard)