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]
- smash 8 and 7 → 1 goes back →
[2, 4, 1, 1, 1] - smash 4 and 2 → 2 goes back →
[2, 1, 1, 1] - smash 2 and 1 → 1 goes back →
[1, 1, 1] - smash 1 and 1 → both gone →
[1] - one stone left →
1
[1, 1] smash equal → empty pile → 0. A single stone [1] is already the answer (1).
Arguments
stones— array of stone weights
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