SDE & MLE Prep

1049. Last Stone Weight II

Problem

Each turn, smash any two stones x ≤ y: equal stones are both destroyed, otherwise one stone of weight y − x remains. Return the smallest possible weight of the last remaining stone (0 if none remains).

Example: [2,7,4,1,8,1] → 1; [31,26,33,21,40] → 5

Constraints: up to 30 stones of weight ≤ 100.

Smashing stones assigns each stone a + or − sign, so the result is |S₁ − S₂| for some split into two groups. Minimize it: find the largest reachable subset sum ≤ total/2 (0/1 knapsack); answer total − 2·best. A Python int works as a bitset of reachable sums.

Complexity: O(n · total) bit operations.

class Solution:
    def lastStoneWeightII(self, stones: List[int]) -> int:
        total, reach = sum(stones), 1               # bit s set <=> some subset sums to s
        for x in stones:
            reach |= reach << x
        best = max(s for s in range(total // 2 + 1) if reach >> s & 1)
        return total - 2 * best