Last Stone Weight II Problem
Description
LeetCode Problem 1049.
You are given an array of integers stones where stones[i] is the weight of the i^th stone.
We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x <= y. The result of this smash is:
- If
x == y, both stones are destroyed, and - If
x != y, the stone of weightxis destroyed, and the stone of weightyhas new weighty - x.
At the end of the game, there is at most one stone left.
Return the smallest possible weight of the left stone. If there are no stones left, return 0.
Example 1:
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We can combine 2 and 4 to get 2, so the array converts to [2,7,1,8,1] then,
we can combine 7 and 8 to get 1, so the array converts to [2,1,1,1] then,
we can combine 2 and 1 to get 1, so the array converts to [1,1,1] then,
we can combine 1 and 1 to get 0, so the array converts to [1], then that's the optimal value.
Example 2:
Input: stones = [31,26,33,21,40]
Output: 5
Constraints:
1 <= stones.length <= 301 <= stones[i] <= 100
Solution
Approach: 0/1 Knapsack
Follow where each stone's weight ends up. Smashing x and y leaves y - x, so in the final weight every stone is counted either with a plus sign or with a minus sign. Splitting the stones into the two groups A (minus) and B (plus), the last stone weighs sum(B) - sum(A). It also works the other way: any split into two groups can be played out by always smashing a stone from each group, so every split is reachable.
So the question becomes: split the stones into two groups whose sums are as close as possible. With total the sum of all stones and a the sum of the lighter group, the result is total - 2a, so we want the largest subset sum a <= total / 2.
That is a 0/1 knapsack over weights. Keep reach[j]: some subset of the stones seen so far sums to exactly j. For each stone w, set reach[j] = true whenever reach[j - w] is true, going from j = total / 2 down to w so that the same stone is not used twice. The answer is total - 2 * (largest reachable j).
Complexity: O(n * S) time and O(S) space, where S is the sum of the stones (at most 3000).
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
total = sum(stones)
half = total // 2
# reach[j]: some subset of the stones weighs exactly j (0/1 knapsack, capacity half).
reach = [True] + [False] * half
for w in stones:
for j in range(half, w - 1, -1): # right to left, so each stone is used once
if reach[j - w]:
reach[j] = True
# The final stone is (total - a) - a for the heaviest subset a <= total / 2.
best = max(j for j in range(half + 1) if reach[j])
return total - 2 * best