Skip to the code
cf.
+10 XP

#378 Last Block Standing

easy

In a small browser game, blocks with weights crash into each other. Each turn, the two heaviest blocks collide. If they weigh the same, both are destroyed. If not, the lighter one is destroyed and the heavier one loses that much weight and stays in the game.

Write lastBlock(weights) that plays until at most one block is left and returns its weight, or 0 if no block is left.

Example 1

Input: weights = [3,9,5,1,10,1]
Output: 1

10 and 9 leave 1; 5 and 3 leave 2; 2 and 1 leave 1; two 1s destroy each other, and one 1 is left.

Example 2

Input: weights = [5,5]
Output: 0

Equal weights destroy each other.

Constraints

  • 1 <= weights.length <= 1000
  • 1 <= weights[i] <= 1000
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).