Menu
CoddyTech

Last Stone Weight

EasyHeappython iconjava iconcpp iconc iconjs icon+10

You have a pile of stones, and stones[i] is the weight of stone i. Each round, take the two heaviest stones and smash them together. If they weigh the same, both are destroyed. If not, the lighter one is destroyed and the heavier one shrinks to the difference of the two weights.

Write lastStoneWeight, which plays rounds until at most one stone is left and returns its weight, or 0 when no stone is left.

Function

lastStoneWeight(stones: integer-array) → integer
stonesinteger-array
the weights of the stones in the pile
Returnsinteger
the weight of the last stone, or 0 if none is left

Constraints

  • 1 ≤ stones.length ≤ 104
  • 1 ≤ stones[i] ≤ 1000

Examples

Input
stones = [3, 9, 4, 6, 2]
Output
0
Explanation
9 and 6 leave a 3, then 4 and 3 leave a 1, then 3 and 2 leave another 1. The two 1 stones destroy each other, so the answer is 0.
challenge icon

Follow-up

The weights are at most 1000. Can you use that bound to finish in O(n + W) time, where W is the largest weight, without a heap?

Reset code
def lastStoneWeight(stones):
    # Write code here

Test #1

Test #2

Test #3

Argument

stones = [3, 9, 4, 6, 2]

Expected Output

0