Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1049 Last Stone Weight II - Walkthrough

Hidden subset sum

Trace Last Stone Weight II on [2,7,4,1,8,1][2, 7, 4, 1, 8, 1]. Total sum is 2323. The insight: smashing stones is like assigning ++ or - signs. Find the lowest PN|P - N| where P+N=23P + N = 23. Find the largest subset sum 23/2=11\leq 23/2 = 11. Using DP: achievable sums include {1,2,3,4,5,7,8,9,11,...}\{1, 2, 3, 4, 5, 7, 8, 9, 11,...\}. Largest sum 11\leq 11 is 1111 (e.g., 7+4=117 + 4 = 11).

Answer: 232×11=123 - 2 \times 11 = 1. The goal is to find the smallest absolute difference, which connects directly to partitioning into equal halves.