Skip to content
DSA Patterns
Menu
Language
Knapsack & Subset DPLC #10496 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Last Stone Weight II

Problem (restated)

Smash two stones a,b: if a≠b a stone of |a-b| remains. Minimize the final stone weight (0 if none).

Intuition

Equivalent to partition stones into two piles with sums as equal as possible; answer is |sum-2S| for best subset sum S ≤ sum/2.

Approaches

Partition closest to half

Unverified
Time O(n·Σ)Space O(Σ)

Idea. Boolean subset-sum DP to target=sum/2; take largest achievable s; return sum-2s.

Walkthrough. [2,7,4,1,8,1] → 1.

Trade-offs. Same core as Partition Equal Subset Sum; minimize difference instead of checking equality.

Solution
export function lastStoneWeightII(stones: number[]): number {
  const total = stones.reduce((a, b) => a + b, 0);
  const target = Math.floor(total / 2);
  const dp = Array(target + 1).fill(false);
  dp[0] = true;
  for (const x of stones) {
    for (let c = target; c >= x; c--) dp[c] = dp[c] || dp[c - x];
  }
  for (let s = target; s >= 0; s--) if (dp[s]) return total - 2 * s;
  return total;
}
export function lastStoneWeightII(stones: number[]): number {
  const total = stones.reduce((a, b) => a + b, 0);
  const target = Math.floor(total / 2);
  const dp = Array(target + 1).fill(false);
  dp[0] = true;
  for (const x of stones) {
    for (let c = target; c >= x; c--) dp[c] = dp[c] || dp[c - x];
  }
  for (let s = target; s >= 0; s--) if (dp[s]) return total - 2 * s;
  return total;
}

Template connection

Split the stones into two groups as close as possible. Boolean subset-sum up to sum / 2 finds the largest achievable s. The difference left is sum - 2 * s.

Reflection

  • The leftover of two piles is sum - 2 * closest, where closest is the subset sum nearest to half the total.
  • This is 0/1 subset sum, so the capacity loop walks backward. One stone is itself. Two equal stones answer 0.
  • The answer is the weight gap between two groups. It is not the order in which stones are smashed.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Last stone weight II: smash [2,7,4,1,8,1]. Each smash is a−b, like putting stones on two piles.

2
0
7
1
4
2
1
3
8
4
1
5

sum = 23

Key:Active rangeMatchSettledEliminated