2-D Dynamic Programming Knapsack
551. Last Stone Weight II
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]
1Explanation: 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]
0Explanation: Smash 6 and 4, which leaves a 2. Smash the two 2s, and no stone is left.
Example 3
Input: stones = [10, 4, 3]
3Explanation: 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.
Constraints
1 ≤ stones.length ≤ 1001 ≤ stones[i] ≤ 1000
Clarifying questions
What you would ask an interviewer before writing any code.