You are given an array of integers stones, where stones[i] is the weight of the i-th stone.
On each turn you choose any two stones and smash them together. Suppose their weights are x and y with x <= y:
-
If
x == y
, both stones are destroyed.
-
If
x != y
, the stone of weight
x
is destroyed, and the stone of weight
y
now weighs
y - x
.
The game ends when at most one stone is left. Return the smallest possible weight of the remaining stone, or 0 if no stone is left.
Function Signature
def smallest_last_stone_weight(stones: list[int]) -> int:
...
Constraints
-
1 <= len(stones) <= 30
-
1 <= stones[i] <= 100
Examples
Input: stones = [2,7,4,1,8,1]
Output: 1
One order that ends at 1: smash 7 and 8 (leaves 1), then 2 and 4 (leaves 2), then that 2 with a 1 (leaves 1), then two of the three remaining 1s. Each smash lowers the total weight by an even amount and the total starts at 23, so the last stone always has odd weight and 0 is impossible.
Input: stones = [31,26,33,21,40]
Output: 5
Smash 40 and 31 (leaves 9), 33 and 26 (leaves 7), 21 and 9 (leaves 12), then 12 and 7, which leaves 5. The total is 151, so the result is odd, and no order ends at 1 or 3.
Input: stones = [10]
Output: 10
With a single stone there is nothing to smash, so its weight is the answer.