1046. Last Stone Weight
Asked at 12Amazon30Bloomberg25Microsoft23Apple22Google21Meta15Salesforce35Nvidia76PayPal63IBM44Visa39Uber22
Problem
Each turn, smash the two heaviest stones x ≤ y together: if they weigh the same both are destroyed, otherwise only a stone of weight y − x remains. Return the weight of the last stone, or 0 if none is left.
Example: [2,7,4,1,8,1] → 1
Simulate with a max-heap: smash the two heaviest, push back the difference.
Complexity: O(n log n).
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
h = [-s for s in stones]
heapify(h)
while len(h) > 1:
a, b = -heappop(h), -heappop(h)
if a != b:
heappush(h, -(a - b))
return -h[0] if h else 0
assert Solution().lastStoneWeight([2, 7, 4, 1, 8, 1]) == 1
assert Solution().lastStoneWeight([1]) == 1
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int s : stones) pq.add(s);
while (pq.size() > 1) {
int a = pq.poll(), b = pq.poll();
if (a != b) pq.add(a - b);
}
return pq.isEmpty() ? 0 : pq.peek();
}
}
type MaxHeap []int
func (h MaxHeap) Len() int { return len(h) }
func (h MaxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h MaxHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *MaxHeap) Push(x any) { *h = append(*h, x.(int)) }
func (h *MaxHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func lastStoneWeight(stones []int) int {
h := MaxHeap(append([]int{}, stones...))
heap.Init(&h)
for h.Len() > 1 { // smash the two heaviest
a, b := heap.Pop(&h).(int), heap.Pop(&h).(int)
if a != b {
heap.Push(&h, a-b)
}
}
if h.Len() == 0 {
return 0
}
return h[0]
}