Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1049 Last Stone Weight II - Hidden Subset Sum

The observation

Here's the key: smashing is just assigning + or - signs to stones. When you smash xx and yy, the result is xy|x - y|. If you trace through all smashes, the final result is +|\sum_{+} - \sum_{-}|.

So the problem becomes: partition stones into two groups to find the smallest absolute difference of their sums. If total sum is SS, and one group sums to PP, the difference is P(SP)=2PS|P - (S - P)| = |2P - S|. To reduce this, find the largest PS/2P \leq S/2 that's achievable. That's subset sum! Run boolean DP up to S/2S/2, find the largest true value, and compute S2PS - 2P.