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
assert Solution().lastStoneWeightII([2, 7, 4, 1, 8, 1]) == 1
assert Solution().lastStoneWeightII([31, 26, 33, 21, 40]) == 5
assert Solution().lastStoneWeightII([1]) == 1
assert Solution().lastStoneWeightII([1, 1]) == 0
class Solution {
public int lastStoneWeightII(int[] stones) {
int total = 0;
for (int s : stones) total += s;
boolean[] dp = new boolean[total / 2 + 1];
dp[0] = true;
for (int s : stones) for (int t = total / 2; t >= s; t--) dp[t] |= dp[t - s];
for (int t = total / 2; ; t--) if (dp[t]) return total - 2 * t;
}
}
func lastStoneWeightII(stones []int) int {
total := 0
for _, x := range stones {
total += x
}
half := total / 2
reach := make([]bool, half+1) // reach[s]: some subset sums to s
reach[0] = true
for _, x := range stones {
for s := half; s >= x; s-- {
reach[s] = reach[s] || reach[s-x]
}
}
best := half // split the stones into two piles as equal as possible
for !reach[best] {
best--
}
return total - 2*best
}