Last Stone Weight

easy heap priority queue

Problem

Each turn, pick the two heaviest stones y ≥ x. If y == x, both shatter. Otherwise the remainder y − x returns. Repeat until at most one stone remains. Return its weight (or 0 if none).

Inputstones = [2, 7, 4, 1, 8, 1]
Output1
8-7=1 → [2,4,1,1,1]; 4-2=2 → [2,1,1,1]; 2-1=1 → [1,1,1]; 1-1=0 → [1]. Answer 1.

import heapq
def last_stone_weight(stones):
    heap = [-s for s in stones]
    heapq.heapify(heap)
    while len(heap) > 1:
        y = -heapq.heappop(heap)
        x = -heapq.heappop(heap)
        if y != x:
            heapq.heappush(heap, -(y - x))
    return -heap[0] if heap else 0
function lastStoneWeight(stones) {
  // simple max-heap via sorted array for clarity
  const heap = stones.slice().sort((a, b) => b - a);
  while (heap.length > 1) {
    const y = heap.shift();
    const x = heap.shift();
    if (y !== x) {
      const d = y - x;
      let i = heap.findIndex(v => v <= d);
      if (i === -1) i = heap.length;
      heap.splice(i, 0, d);
    }
  }
  return heap[0] || 0;
}
class Solution {
    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 (y != x) heap.offer(y - x);
        }
        return heap.isEmpty() ? 0 : heap.peek();
    }
}
int lastStoneWeight(vector<int>& stones) {
    priority_queue<int> heap(stones.begin(), stones.end());
    while (heap.size() > 1) {
        int y = heap.top(); heap.pop();
        int x = heap.top(); heap.pop();
        if (y != x) heap.push(y - x);
    }
    return heap.empty() ? 0 : heap.top();
}
Time: O(n log n) Space: O(n)