oneby7

Heaps Simulating with a heap

414. Last Stone Weight

Easy 147 DSA Sheet

You are given an array stones, where stones[i] is the weight of the i-th stone. The stones are smashed together, two at a time, in turns.

In each turn, the two heaviest stones are smashed together. Their weights are x and y, with x ≤ y. If x == y, both stones are destroyed. Otherwise the stone of weight x is destroyed, and the other stone now weighs y − x and goes back with the rest.

The turns go on until at most one stone is left. Return the weight of that stone, or 0 if no stone is left.

Example 1

Input: stones = [4, 9, 2, 7, 3]

Output: 1

Explanation: 9 and 7 leave a stone of 2. Then 4 and 3 leave a stone of 1. The two stones of 2 destroy each other, and the stone of 1 is left.

Example 2

Input: stones = [5, 3, 8]

Output: 0

Explanation: 8 and 5 leave a stone of 3. It meets the other stone of 3, and both are destroyed, so no stone is left.

Example 3

Input: stones = [1000000000]

Output: 1000000000

Explanation: There is only one stone, so no turn happens.

Check your understanding

Work out the answer for this input before you write any code.

stones = [9, 2, 2, 1]

Constraints

  • 1 ≤ stones.length ≤ 105
  • 1 ≤ stones[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.