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 y≥xy \geq x)
  • If y>xy > x, insert y−xy - 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(log⁡n)O(\log n) per turn, at most nn turns. Time: O(nlog⁡n)O(n \log n). Space: O(n)O(n).