oneby7

2-D Dynamic Programming Knapsack

551. Last Stone Weight II

Medium

You are given an array stones, where stones[i] is the weight of the i-th stone. You smash the stones together, two at a time, until at most one stone is left.

On each turn you pick any two stones. Say their weights are x and y, with x ≤ y. If x == y, both stones are destroyed. Otherwise the lighter stone is destroyed, and the heavier one now weighs y − x.

Return the smallest weight the last stone can have. If no stone is left, return 0.

Example 1

Input: stones = [5, 9, 3, 8, 2]

Output: 1

Explanation: Smash 9 and 8, which leaves a 1. Smash 5 and 3, which leaves a 2. Smash that 2 with the other 2, and both are destroyed. The stone of weight 1 is left, and no order of smashes destroys every stone.

Example 2

Input: stones = [2, 4, 6]

Output: 0

Explanation: Smash 6 and 4, which leaves a 2. Smash the two 2s, and no stone is left.

Example 3

Input: stones = [10, 4, 3]

Output: 3

Explanation: Smash 10 and 4, which leaves a 6, then 6 and 3, which leaves a 3. Smashing 4 and 3 first would leave a 1, and then 10 and 1 leave a 9.

Check your understanding

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

stones = [6, 7, 5, 5, 7]

Constraints

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

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.