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 a function named lastStoneWeight that plays rounds until at most one stone is left, and returns the weight of that stone, 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 stones of weight 1 destroy each other, so nothing is left and the answer is 0.

lock icon+13 hidden tests on Submit

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 cases

Case 1

Case 2

Case 3

Input

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

Expected

0