Data Structures19 sections · 729 units
Open in Course

Last Stone - Algorithm

Max-heap simulation

Use a max-heap to always get the two heaviest stones:

1.1. Insert all stones into a max-heap.

2.2. While heap has more than one stone:

  • Extract the two largest: yy and xx (with yxy \geq x)
  • If y>xy > x, insert yxy - x back into the heap

3.3. Return the remaining stone's weight, or 00 if empty. Each smash involves at most two extractions and one insertion: O(logn)O(\log n) per turn, at most nn turns. Time: O(nlogn)O(n \log n). Space: O(n)O(n).