Leetcode 1046. Last Stone Weight
We are given a list of stones’ weights. 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:
x == y
, both stones are destroyed.x != y
, the stone of weight x
is destroyed, and the stone of weight y
has a new weight y - x
.At the end of the game, there is at most one stone left. Return the weight of this stone (or 0 if there are no stones left.)
[2,7,4,1,8,1]
1
n
could be up to 30.PriorityQueue
with Collections.reverseOrder to simulate max-heap.import java.util.PriorityQueue;
import java.util.Collections;
public class LastStoneWeight {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
// Add all stones to the max heap
for (int stone : stones) {
maxHeap.add(stone);
}
// Process the stones
while (maxHeap.size() > 1) {
int first = maxHeap.poll();
int second = maxHeap.poll();
if (first != second) {
maxHeap.add(first - second);
}
}
return maxHeap.isEmpty() ? 0 : maxHeap.poll();
}
public static void main(String[] args) {
LastStoneWeight solution = new LastStoneWeight();
int[] stones = {2, 7, 4, 1, 8, 1};
System.out.println(solution.lastStoneWeight(stones)); // Output: 1
}
}
n
is the number of stones.n-1
such operations.Overall, the time complexity is approximately O(n log n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?