You are given an array of integers stones, where stones[i] is the weight of the i-th stone.
The stones are smashed together one turn at a time. On each turn, take the two heaviest stones, with weights x <= y, and smash them:
- If
x == y, both stones are destroyed. - If
x < y, the lighter stone is destroyed and the heavier one now weighsy - x. It goes back into the pile.
The game ends when at most one stone is left. Return the weight of that last stone, or 0 if no stones are left.
Examples
Example 1
Input: stones = [2,7,4,1,8,1]
Output: 1
- Smash 8 and 7. A stone of weight 1 goes back:
[2,4,1,1,1] - Smash 4 and 2. A stone of weight 2 goes back:
[2,1,1,1] - Smash 2 and 1. A stone of weight 1 goes back:
[1,1,1] - Smash 1 and 1. Both are destroyed:
[1]
One stone of weight 1 is left.
Example 2
Input: stones = [9,3,2]
Output: 4
Smashing 9 and 3 leaves a stone of weight 6. That new stone is now the heaviest in the pile, so the next turn smashes 6 and 2, leaving 4. The leftover stone has to go back into the pile, and it can come straight back out as the heaviest.
Example 3
Input: stones = [3,3]
Output: 0
The two stones weigh the same, so both are destroyed and nothing is left.
Example 4
Input: stones = [1]
Output: 1
There is only one stone, so there is nothing to smash.
Example 5
Input: stones = [2,3,6,2,4]
Output: 1
- Smash 6 and 4. A stone of weight 2 goes back:
[2,3,2,2] - Smash 3 and 2. A stone of weight 1 goes back:
[2,2,1] - Smash 2 and 2. Both are destroyed:
[1]
Constraints
1 <= stones.length <= 301 <= stones[i] <= 1000