AlgoLounge

Last Stone Weight

easy

You are given an array of integers stones where stones[i] represents the weight of the i^(th) stone.

We want to run a simulation on the stones as follows:

  • At each step, we choose the two heaviest stones, with weight x and y and smash them together
  • If x == y, both stones are destroyed
  • If x < y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.

Return the weight of the last remaining stone or return 0 if none remain.

Examples

Example 1

Input:  stones = [2,3,6,2,4]
Output: 1

We smash 6 and 4 and get 2, so the array becomes [2,3,2,2]. Then we smash 3 and 2 and get 1, so the array becomes [2,2,1]. Then we smash 2 and 2, so the array becomes [1].

Example 2

Input:  stones = [1,2]
Output: 1

Constraints

  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 100
TypeScript
Loading editor…
List of test cases (10)
Case 1
stones = [2,3,6,2,4]
Case 2
stones = [1,2]
Case 3
stones = [1]
Case 4
stones = [2,2]
Case 5
stones = [7,6,7,6,9]
Case 6
stones = [1,3]
Case 7
stones = [3,7,2]
Case 8
stones = [10,4,2,10]
Case 9
stones = [1,1,2,3,5]
Case 10
stones = [100,90,80,70,60,50,40,30,20,10]