Start learning free

LESSON 461 OF 678 · HEAP

Last Stone Weight

Practice O(n log n)

You get an array stones. Each number is the weight of one stone in a pile.

Each turn, smash the two heaviest stones together. If they weigh the same, both break. If not, the lighter one breaks. The heavier one loses that much weight. For example, stones of 9 and 4 leave one stone of 5.

Repeat until one stone or none is left. Return the weight of that stone, or 0 if none is left.

 

Example 1:

Input: stones = [12, 5, 4, 1]
Output: 2
Explanation: 
Smash 12 and 5. The pile is now [7, 4, 1].
Smash 7 and 4. The pile is now [3, 1].
Smash 3 and 1. Only a stone of 2 is left.

Example 2:

Input: stones = [8, 3, 7, 4]
Output: 0
Explanation: 
Smash 8 and 7. The pile is now [3, 4, 1].
Smash 4 and 3. The pile is now [1, 1].
The two 1s weigh the same, so both break.
Nothing is left.

Example 3:

Input: stones = [6, 6, 6]
Output: 6
Explanation: Two of the 6s smash, and both break.
The third 6 is left.

 

Constraints:

  • 2 to 30,000 stones.
  • Each weight is a whole number from 0 to 100,000,000.
STEP 1 OF 8
    Ctrl + Enter to check