Last Stone Weight II
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #1049
Smashing two stones x ≤ y leaves a stone of weight y − x (nothing if they're equal). Keep smashing until at most one stone remains. Return the smallest possible weight of the last stone (0 if none remain).
Examples
text
[2,7,4,1,8,1] → 1
[31,26,33,21,40] → 5Hints
- Track the signs: every stone ends up added or subtracted in the final result.
- So the answer is the minimum of
|S₁ − S₂|over all splits of the stones into two groups. That's subset sum.
Approach
The final weight equals |sum(A) − sum(B)| for some partition A/B, and every partition can be achieved by some smashing order. So:
total = sum(stones). Find the largest achievable subset sums ≤ total // 2(0/1 knapsack with a booleandp, iterating the sum backwards so each stone is used once).- The answer is
total − 2s.
A Python bitset makes it a one-liner: bits |= bits << w. O(n · total).
Complexity
Time: O(n · total). Space: O(total).
Python solution
def lastStoneWeightII(stones):
total = sum(stones)
bits = 1
for w in stones:
bits |= bits << w
for s in range(total // 2, -1, -1):
if bits >> s & 1:
return total - 2 * sJavaScript solution
function lastStoneWeightII(stones) {
const total = stones.reduce((a, b) => a + b, 0), half = Math.floor(total / 2);
const dp = new Array(half + 1).fill(false);
dp[0] = true;
for (const w of stones) for (let s = half; s >= w; s--) if (dp[s - w]) dp[s] = true;
for (let s = half; s >= 0; s--) if (dp[s]) return total - 2 * s;
return total;
}