#1046

Last Stone Weight

pupil · 315 · lc easy +21 · verified · 66.4% accepted · 6,626 likes · top 72%

Description

You are given an array stones where stones[i] is the weight of the ith stone. Each turn, pick the two heaviest stones (weights x <= y) and smash them: if x == y both are destroyed; otherwise the stone of weight x is destroyed and the stone of weight y becomes y - x.

Repeat until at most one stone remains. Return its weight, or 0 if none remain.

Example 1:

Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.

Example 2:

Input: stones = [1]
Output: 1

Code

1
2
3