Crate Crusher

Easy · Heaps & Top-K · about 15 min

A recycling press works on a pile of crates, given by their weights. Each round it takes the two heaviest crates, with weights x >= y:

  • if x == y, both crates are crushed and gone,
  • otherwise the lighter one is crushed and the heavier one comes back with weight x - y.

The press stops when fewer than two crates are left. Return the weight of the last crate, or 0 if none is left.

Example: crush_crates([2, 7, 4, 1, 8, 1]) → 1 (8 and 7 leave 1; 4 and 2 leave 2; 2 and 1 leave 1; 1 and 1 are both crushed; one crate of weight 1 is left)

Hints

  • You always need the two largest values, and a new value goes back in after each round. That is a job for a max-heap.
  • Python's heapq only gives the smallest item, so push negative weights and flip the sign when you pop.
  • Push the difference back only when the two weights are different.

Learn the pattern first: the Heaps & Top-K lesson.

More Heaps & Top-K problems