#1049
Last Stone Weight II
specialist · 720 · lc medium +30 · verified · 59.3% accepted · 3,371 likes · top 57%
Description
You are given an array stones where stones[i] is the weight of the ith stone. On each turn, choose any two stones (weights x <= y) and smash them: if equal both vanish; otherwise the stone of weight x is destroyed and y becomes y - x.
Return the smallest possible weight of the last stone. Return 0 if no stones remain.
Example 1:
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.
Example 2:
Input: stones = [31,26,33,21,40]
Output: 5
Code
1
2
3