dsa · easy

Last Stone Weight

You have a pile of stones. stones[i] is the weight of the i-th stone.

While at least two stones remain, smash the **two heaviest**. Call their weights y ≥ x: - if x == y, both are destroyed - otherwise both are destroyed and a new stone of weight y - x goes back in the pile

When fewer than two stones remain, return the last stone's weight, or 0 if the pile is empty. Always taking the two heaviest matters — smashing an arbitrary pair can give a different answer.

Example

stones = [2, 7, 4, 1, 8, 1]

[1, 1] smash equal → empty pile → 0. A single stone [1] is already the answer (1).

Arguments

Constraints

1 <= stones.length <= 30, 1 <= stones[i] <= 1000 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[2,7,4,1,8,1]

Expected:
1

Example 2

Input:
[1]

Expected:
1

Example 3

Input:
[1,1]

Expected:
0

Open in the Dojo editor