{"id":"last-stone-weight-ii","title":"Last Stone Weight II","difficulty":"medium","patterns":["dp-knapsack"],"primaryConcept":"dp-knapsack-boolean","concepts":["dp-knapsack-boolean"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array","primaryParam":"stones","sizeMetric":"array-length","constraints":["positive"],"sizes":[8,16,32,64],"valueRange":{"min":1,"max":100}},"description":"You are given an array `stones` where `stones[i]` is the weight of the ith stone.\n\nOn each turn, choose any two stones and smash them together. If their weights are equal, both are destroyed. If their weights are different, the smaller stone is destroyed and the larger stone's weight becomes the difference.\n\nReturn the smallest possible final stone weight.","examples":[{"input":"stones = [2,7,4,1,8,1]","output":"1","explanation":"An optimal sequence of smashes leaves one stone of weight 1."},{"input":"stones = [31,26,33,21,40]","output":"5","explanation":"An optimal sequence of smashes leaves one stone of weight 5."}],"constraints":[{"id":"1-len-stones-30","text":"1 <= len(stones) <= 30","check":{"kind":"sizeRange","target":"stones","measure":"arrayLength","min":1,"max":30}},{"id":"1-stones-i-100","text":"1 <= stones[i] <= 100","check":{"kind":"valueRange","target":"stones","selector":"arrayItems","min":1,"max":100}}],"starterCode":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        # Your code here\n        pass","functionName":"lastStoneWeightII","testCases":[{"id":"1","input":{"stones":[2,7,4,1,8,1]},"expected":1,"description":"Classic sample with closest sums 11 and 12."},{"id":"2","input":{"stones":[31,26,33,21,40]},"expected":5,"description":"Large weights where the closest split differs by five."},{"id":"3","input":{"stones":[1,2]},"expected":1,"description":"Two stones leave their absolute difference."},{"id":"4","input":{"stones":[10,10]},"expected":0,"description":"Equal stones can destroy each other completely."},{"id":"5","input":{"stones":[1,1,4,2,2]},"expected":0,"description":"A perfect balanced split exists."},{"id":"hidden-1","input":{"stones":[7]},"expected":7,"description":"A single stone remains unchanged."},{"id":"hidden-2","input":{"stones":[1,1,1,1,1]},"expected":1,"description":"Odd total weight cannot split evenly."},{"id":"hidden-3","input":{"stones":[9,3,2,10]},"expected":0,"description":"A subset of 12 balances the total weight of 24."},{"id":"hidden-4","input":{"stones":[8,6,5]},"expected":3,"description":"The closest half-sum is 8, leaving 11 on the other side."},{"id":"hidden-5","input":{"stones":[3,7,2,9,4]},"expected":1,"description":"A subset reaches 12 out of total 25."},{"id":"large-unbalanced-partition","input":{"stones":[10,10,10,10]},"expected":0,"description":"Larger weights still reduce to the closest subset-sum difference."},{"id":"classic-odd-total-near-balance","input":{"stones":[1,2,5]},"expected":2,"description":"An odd total can still be partitioned to leave only one weight."}],"hints":[{"level":1,"content":"Think of the final weight as the difference between two groups of stones."},{"level":2,"content":"To minimize the difference, find the largest reachable subset sum that does not exceed total // 2."},{"level":3,"content":"Use a backward 0/1 knapsack update so each stone contributes at most once to the reachable subset sums.","revealPattern":true}],"guidedFlow":{"version":2,"progressRevision":"last-stone-weight-ii-2026-07-19-dp-state-ladder","approachSelection":{"contract":"approach-selection-v1","question":"How should we minimize the final difference?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"simulate-largest","name":"Greedy simulation","summary":"Repeatedly smash the two largest stones.","decisionReason":"Fast, but it commits to the locally largest smash and can miss the globally closest split. On stones = [40,33,31,26,21] it smashes down to a leftover of 9, while the closest split actually leaves 5.","complexity":{"time":"O(n log n)","space":"O(n)"},"tradeoffs":["Each step picks the locally largest pair, which is not the choice that minimizes the final gap."],"isOptimal":false},{"id":"brute-force-subsets","name":"Try every subset","summary":"Enumerate every possible group assignment and keep the smallest difference.","decisionReason":"Each stone doubles the assignments, so it explores 2^n splits, over a billion at the 30-stone limit, re-deriving the same group sums on countless paths.","complexity":{"time":"O(2^n)","space":"O(1)"},"tradeoffs":["The 2^n group assignments make it intractable once n grows past roughly 30."],"isOptimal":false},{"id":"subset-sum-dp","name":"Boolean subset-sum DP","summary":"Track which sums up to total // 2 are reachable and keep the largest reachable one.","decisionReason":"It keeps exactly the state that matters, the set of reachable group sums up to half the total, so the billion brute-force paths collapse into one settled answer per sum and it reads off the closest half directly.","complexity":{"time":"O(n * s)","space":"O(s)"},"tradeoffs":["Stores one bit per reachable sum up to half the total, settling each sum once instead of re-exploring it."],"isOptimal":true}]},"codingCheckpoints":[{"id":"calculate-total","title":"Compute total weight","description":"Sum all stone weights so the problem can be reframed as a split.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_input_aggregate","scope":"calculate-total","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Compute the total weight across all stones.","doneWhen":"This step is done when the code derives a total from the input stones before creating the DP table.","shouldFailWhen":"This step should fail if the total is hard-coded or does not aggregate the input stones.","roles":["stones","total weight","group difference"],"mustProve":["The code aggregates all input stone weights.","The aggregate is available before the subset target is computed."],"mustNotAccept":["Using only the largest stone as the total.","Skipping the total and simulating greedy smashes."],"equivalentVariants":["Use sum(stones).","Use a loop that accumulates every stone weight."],"proofSnippets":[{"id":"py-last-stone-ii-calculate-total","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        return 0"}]},"commonMistakes":["Trying to model the smash operations directly","Using only part of the array when computing total"],"hint":"The final weight is the difference between two group sums, so first compute their combined sum."},{"id":"calculate-target","title":"Target half the total","description":"Compute the largest subset sum we need to consider.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_half_total_target","scope":"calculate-target","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Limit the subset-sum search to half of the total weight.","doneWhen":"This step is done when the code derives target = total // 2 or an equivalent half-total capacity.","shouldFailWhen":"This step should fail if the target is unrelated to total or if it searches all sums unnecessarily.","roles":["total weight","half capacity","closest subset"],"mustProve":["The target is derived from the total weight.","The target represents the half-sum boundary."],"mustNotAccept":["Using max(stones) as the target.","Using the full total as the DP capacity."],"equivalentVariants":["Use total // 2.","Use floor(total / 2) in another language."],"proofSnippets":[{"id":"py-last-stone-ii-calculate-target","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        return 0"}]},"commonMistakes":["Targeting the full total instead of half","Forgetting that a subset above half has a mirrored complement below half"],"hint":"The closer one group is to total // 2, the smaller the final difference becomes."},{"id":"init-dp","title":"Create reachable-sum table","description":"Allocate a boolean table for sums from 0 through target.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_boolean_subset_table","scope":"init-dp-array","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Create a boolean DP table where dp[w] means some processed subset can sum to w.","doneWhen":"This step is done when the code allocates target + 1 boolean cells before processing stones.","shouldFailWhen":"This step should fail if the table is missing, numeric counts are used for the wrong recurrence, or the capacity is too small.","roles":["boolean DP table","reachable sum","target capacity"],"mustProve":["The table covers every capacity from 0 through target.","The table is initialized before any stone transitions."],"mustNotAccept":["Using a scalar best value without reachable state.","Allocating only target cells and missing index target."],"equivalentVariants":["Use a boolean list of length target + 1.","Use an equivalent indexed reachable-state table."],"proofSnippets":[{"id":"py-last-stone-ii-init-dp","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        return 0"}]},"commonMistakes":["Allocating a table up to total instead of target","Forgetting that index target must be included"],"hint":"Each index in dp is a possible subset weight."},{"id":"set-base-case","title":"Seed sum zero","description":"Mark sum 0 as reachable before using any stones.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"sets_zero_subset_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Represent the empty subset as a reachable sum of zero.","doneWhen":"This step is done when dp[0] is set to true before the nested loops.","shouldFailWhen":"This step should fail if dp[0] remains false or if the base case is set after transitions.","roles":["empty subset","zero sum","base cell"],"mustProve":["The zero-sum cell is marked reachable.","The base case is established before processing stones."],"mustNotAccept":["Seeding dp[target] instead of dp[0].","Skipping the base case and relying on accidental truthy values."],"equivalentVariants":["Set dp[0] to True.","Use an equivalent boolean reachable-state seed at sum zero."],"proofSnippets":[{"id":"py-last-stone-ii-set-base-case","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        return 0"}]},"commonMistakes":["Forgetting that the empty subset is needed to start transitions","Setting the wrong DP index to true"],"hint":"Before picking any stones, sum 0 is reachable."},{"id":"backward-transition","title":"Run backward subset transitions","description":"For each stone, update reachable weights from target down to the stone weight.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"uses_backward_subset_transition","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Use each stone at most once while updating reachable subset sums.","doneWhen":"This step is done when every stone drives a descending capacity loop and dp[weight] considers dp[weight - stone].","shouldFailWhen":"This step should fail if the capacity loop runs forward or if the recurrence can reuse a stone in the same pass.","roles":["current stone","descending capacity","previous reachable sum"],"mustProve":["Each stone is processed in an outer loop.","The inner capacity loop moves downward from target to the current stone."],"mustNotAccept":["Iterating capacities upward.","Updating dp[weight] without referencing dp[weight - stone]."],"equivalentVariants":["Use range(target, stone - 1, -1).","Use any descending loop shape that preserves 0/1 single-use behavior."],"proofSnippets":[{"id":"py-last-stone-ii-backward-transition","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        for stone in stones:\n            for weight in range(target, stone - 1, -1):\n                dp[weight] = dp[weight] or dp[weight - stone]\n        return 0"}]},"commonMistakes":["Looping weight upward and using a stone more than once","Checking dp[stone - weight] instead of dp[weight - stone]"],"hint":"Backward capacity order is what makes this 0/1 knapsack instead of unbounded knapsack."},{"id":"track-best","title":"Track the closest reachable half","description":"Remember the largest reachable subset sum that does not exceed target.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Maintain the best reachable weight seen so far during the DP traversal.","doneWhen":"This step is done when the code updates a numeric best state from a reachable capacity.","shouldFailWhen":"This step should fail if the best value is never updated or if it ignores reachability.","roles":["best reachable weight","current capacity","reachable state"],"mustProve":["The code tracks a numeric maximum.","The maximum is updated from a capacity that the DP has marked reachable."],"mustNotAccept":["Returning the largest stone weight.","Updating best without checking reachability."],"equivalentVariants":["Use best = max(best, weight) when dp[weight] is reachable.","Track the same maximum reachable capacity through an equivalent numeric state."],"proofSnippets":[{"id":"py-last-stone-ii-track-best","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        best = 0\n        for stone in stones:\n            for weight in range(target, stone - 1, -1):\n                dp[weight] = dp[weight] or dp[weight - stone]\n                if dp[weight]:\n                    best = max(best, weight)\n        return 0"}]},"commonMistakes":["Tracking the first reachable weight instead of the largest","Updating best before dp[weight] has been updated"],"hint":"The closest split is the maximum reachable weight at or below target."},{"id":"return-difference","title":"Return the minimum difference","description":"Convert the best half-sum into the final stone weight.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_difference_between_numeric_states","scope":"compute-gap","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the difference between the total weight and twice the best reachable half-sum.","doneWhen":"This step is done when the code returns total - 2 * best or an equivalent group-sum difference.","shouldFailWhen":"This step should fail if the code returns best itself, target - best, or an unrelated DP cell.","roles":["total weight","best reachable half","minimum difference"],"mustProve":["The returned value combines total and the tracked best reachable half.","The formula represents the difference between the two group sums."],"mustNotAccept":["Returning best instead of the leftover difference.","Returning total - best instead of total - 2 * best."],"equivalentVariants":["Return total - 2 * best.","Return abs((total - best) - best)."],"proofSnippets":[{"id":"py-last-stone-ii-return-difference","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        best = 0\n        for stone in stones:\n            for weight in range(target, stone - 1, -1):\n                dp[weight] = dp[weight] or dp[weight - stone]\n                if dp[weight]:\n                    best = max(best, weight)\n        return total - 2 * best"}]},"commonMistakes":["Returning best instead of the final difference","Subtracting best only once from total"],"hint":"One group has weight best; the other has weight (total - best)."}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The smashing","eyebrow":"Read the problem","title":"Smash stones down to the smallest leftover","workspacePanel":"problem","body":["You get an array of stone weights. Each turn smashes two stones together: equal weights destroy each other, unequal weights leave a stone of their difference. Return the smallest weight that can be left at the end.","The order of smashes is wide open, and different orders can leave different stones behind. The safe first move is to explore the smash choices exhaustively and keep the smallest leftover. Watch what that costs."]},{"id":"brute-force","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Try every way to split the stones","summary":"Branching every stone onto one side or the other tries every split and keeps the closest, which is correct but re-solves the same group sums down countless paths. Watch how often it lands on a sum it has already settled.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def lastStoneWeightII(stones: list[int]) -> int:\n    target = sum(stones) // 2\n    def best(i: int, s: int) -> int:\n        if i == len(stones):\n            return s if s <= target else 0\n        take = best(i + 1, s + stones[i])\n        skip = best(i + 1, s)\n        return max(take, skip)\n\n    return best(0, 0)","steps":[{"id":"fork-first","title":"Each stone forks the search","codeLine":6,"summary":"Walking [2, 7, 4, 1, 8, 1], send stones[0] = 2 onto one side so its group sum s becomes 2, or leave it off so s stays 0. Every stone forks the search in two.","state":{"i":0,"s":0,"total":23,"labels":{}}},{"id":"reaches-seven","title":"One branch takes only the 7, reaching group sum 7","codeLine":7,"summary":"Through stones[0..3] = [2, 7, 4, 1], one branch skips the 2, takes the 7, then skips the 4 and the 1, landing that group's sum at 7.","state":{"i":4,"s":7,"total":23}},{"id":"reaches-seven-again","title":"Another branch takes 2, 4, and 1, reaching the same group sum 7","codeLine":8,"summary":"A different branch through the same stones[0..3] takes the 2, the 4, and the 1 while skipping the 7, and also lands at sum 7, so the search below this point re-solves the very same remaining stones [8, 1].","state":{"i":4,"s":7,"total":23}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const target = Math.floor(stones.reduce((total, value) => total + value, 0) / 2);\nfunction best(i, s) {\n    if (i == stones.length) {\n        return (s <= target ? s : 0);\n    }\n    const take = best((i + 1), (s + stones[i]));\n    const skip = best((i + 1), s);\n    return Math.max(take, skip);\n}\nreturn best(0, 0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"10":10},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const target = Math.floor(stones.reduce((total, value) => total + value, 0) / 2);\nfunction best(i: number, s: number): number {\n    if (i == stones.length) {\n        return (s <= target ? s : 0);\n    }\n    const take = best((i + 1), (s + stones[i]));\n    const skip = best((i + 1), s);\n    return Math.max(take, skip);\n}\nreturn best(0, 0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"10":10},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int target = stones.Sum() / 2;\nint Best(int i, int s) {\n    if (i == stones.Count) {\n        return (s <= target ? s : 0);\n    }\n    int take = Best(i + 1, s + stones[i]);\n    int skip = Best(i + 1, s);\n    return Math.Max(take, skip);\n    return 0;\n}\nreturn Best(0, 0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"10":11},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int, int)> best;\n\nint target = accumulate(stones.begin(), stones.end(), 0) / 2;\nbest = [&]( int i, int s ) -> int {\n    if (i == stones.size()) {\n        return (s <= target ? s : 0);\n    }\n    int take = best((i + 1), (s + stones[i]));\n    int skip = best((i + 1), s);\n    return max(take, skip);\n};\nreturn best(0, 0);","lineMap":{"2":3,"4":5,"5":6,"6":8,"7":9,"8":10,"10":12},"statementBundles":{"2":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int best(int i, int s, List<Integer> stones, int target) {\n    if (i == stones.size()) {\n        return (s <= target ? s : 0);\n    }\n    int take = best((i + 1), (s + stones.get(i)), stones, target);\n    int skip = best((i + 1), s, stones, target);\n    return Math.max(take, skip);\n}\n\nint target = Math.floorDiv(stones.stream().mapToInt(Integer::intValue).sum(), 2);\nreturn best(0, 0, stones, target);","lineMap":{"2":10,"4":2,"5":3,"6":5,"7":6,"8":7,"10":11},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8}}}}},"body":["For each stone, branch on whether it joins this group or the other, and at the end keep the split whose two group sums sit closest together."]},{"id":"repeated-work","kind":"case-probe","chapter":"The obvious way","eyebrow":"Name the waste","title":"What does the branching keep redoing?","workspacePanel":"visualizer","summary":"Two different branches just landed on the same displayed state, i = 4 with group sum s = 7, and the search keeps going from each one separately.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-state","state":{"nums":[2,7,4,1,8,1],"i":4,"groupSum":7,"total":23,"labels":{"nums":"stones"}}}]},"options":[{"id":"subsum","label":"Whether some group of the stones seen so far reaches a given sum, re-checked on every path that lands on that sum","rationale":"Each stone forks the search in two, so n stones build 2^n branches, over a billion at the 30-stone limit. Yet once a path reaches a group sum like 7, how close the remaining stones can push it toward half depends only on that sum, not on which stones built it. The 2^n leaves collapse because there are only a few hundred distinct group sums to settle. Deciding each group sum once and storing it removes the repetition.","isCorrect":true},{"id":"reading","label":"Reading each stone weight out of the array","rationale":"Looking up one array slot is cheap. The expense is re-exploring the same group sum down many branches.","isCorrect":false},{"id":"compare","label":"Comparing the two branch results to keep the closer one","rationale":"The keep-the-closer combine is one cheap step. The waste is the search beneath it rebuilding answers for group sums it has already settled.","isCorrect":false}],"answer":"Whether a group of stones can reach a given sum. The branch tree has 2^n leaves, over a billion at 30 stones, but that answer is fixed for a given sum, so deciding each reachable sum once and remembering it collapses the billion leaves into a few hundred distinct sums."},{"id":"reduce-to-half","kind":"case-probe","chapter":"The idea","eyebrow":"Reframe the goal","title":"Minimizing the leftover means making one group land where?","workspacePanel":"visualizer","summary":"The total of [2, 7, 4, 1, 8, 1] is 23, and the leftover is the gap between the two group sums.","options":[{"id":"close-to-half","label":"As close as possible to half the total, without going over","rationale":"If one group sums to g, the other sums to 23 - g, and the leftover is their gap, 23 - 2g. That gap shrinks as g climbs toward half the total, 11. So the goal is the largest reachable group sum at or below 11.","isCorrect":true},{"id":"largest-first","label":"Hold the largest stone alone and split the rest around it","rationale":"Fixing the biggest stone alone can strand a better split. For [2, 7, 4, 1, 8, 1] the closest split mixes several stones to reach 11, which isolating 8 misses.","isCorrect":false},{"id":"exact-half","label":"Exactly half the total, or there is no answer","rationale":"The total 23 is odd, so no group hits exactly 11.5. The leftover is still minimized by getting as near to half as a real subset allows, here 11.","isCorrect":false}],"answer":"As close to half the total as possible without exceeding it. With total 23 the leftover is 23 - 2g, so the largest reachable group sum at or below 11 makes the gap smallest.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"half-state","state":{"nums":[2,7,4,1,8,1],"total":23,"target":11,"labels":{"nums":"stones"}}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"nums":[2,7,4,1,8,1],"total":23,"target":11,"labels":{"nums":"stones"}}}]}},{"id":"table-setup","kind":"info","chapter":"The idea","eyebrow":"Introduce the state","title":"One cell for each possible half-sum","workspacePanel":"visualizer","body":["Use a boolean table dp over sums 0 through 11. Each cell records one answer about the stones processed so far; define that answer before filling any cell."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"empty-reachability-table","state":{"dp":[0,0,0,0,0,0,0,0,0,0,0,0],"i":0}}]}},{"id":"state-definition","kind":"case-probe","chapter":"The idea","eyebrow":"Define the state","title":"After some stones are processed, what does dp[w] mean?","summary":"The table has one boolean cell for every group sum w from 0 through 11.","workspacePanel":"visualizer","options":[{"id":"reachable-subset-sum","label":"Whether a subset of the processed stones has total weight exactly w","rationale":"dp[w] answers whether the stones already processed can form group sum w. That meaning lets each new stone extend only sums that were already reachable.","isCorrect":true},{"id":"best-gap-so-far","label":"The smallest leftover obtainable after processing w stones","rationale":"w indexes a possible group sum. The boolean cell records whether the processed stones can reach that exact weight."},{"id":"stone-used-at-sum","label":"Whether the stone whose weight is w has already been used","rationale":"The index names a target group sum even when no stone weighs w. The table tracks reachable weights, not individual stone usage."}],"answer":"dp[w] is true exactly when some subset of the stones processed so far sums to w. The table therefore remembers the repeated reachability question that the branch search kept recomputing.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-definition-table","state":{"dp":[0,0,0,0,0,0,0,0,0,0,0,0],"i":7}}]}},{"id":"base-case","kind":"case-probe","chapter":"The idea","eyebrow":"Set the floor","title":"Before any stone is placed, which group sums are reachable?","summary":"The rule grows reachable sums outward, so it needs a seed to grow from.","workspacePanel":"visualizer","options":[{"id":"only-zero","label":"Only sum 0, reachable by placing nothing on the group","rationale":"An empty group sums to 0, so 0 is reachable before any stone. Every other sum starts unreachable until a stone lands on it.","isCorrect":true},{"id":"all-reachable","label":"Every sum from 0 to 11","rationale":"Most sums are not reachable yet, with no stones placed. Seeding them all reachable would claim group sums no subset can actually make.","isCorrect":false},{"id":"none","label":"No sums at all, the table starts empty","rationale":"Then the rule has nothing to extend: 0 + stone would never fire. Sum 0 must be the one reachable seed the stones build from.","isCorrect":false}],"answer":"Only sum 0, because an empty group already makes it. Every other sum starts unreachable, and a stone marks a new sum only by landing on a sum already reachable.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"base-state","state":{"dp":[1,0,0,0,0,0,0,0,0,0,0,0],"i":0}}]}},{"id":"transition","kind":"case-probe","chapter":"The idea","eyebrow":"Build the rule","title":"Given the sums reachable so far, which new sums does adding a stone unlock?","summary":"The next stone has weight 7. Before it, the reachable group sums are {0, 2}.","workspacePanel":"visualizer","options":[{"id":"plus-num","label":"Every already-reachable sum, plus that same sum with the stone added","rationale":"Adding 7 to each reachable sum makes 0 + 7 = 7 and 2 + 7 = 9 newly reachable, on top of 0 and 2 which stay reachable by leaving the 7 off this group.","isCorrect":true},{"id":"only-num","label":"Only the stone's own weight becomes reachable","rationale":"The 7 can be added to any earlier reachable sum. It unlocks 9 as well as 7, because 2 was already reachable.","isCorrect":false},{"id":"all-up-to","label":"Every sum from 0 up to the stone's weight becomes reachable","rationale":"Sums 1, 3, 4, 5, 6 stay out of reach: no group of the stones seen so far hits them. Only old sums shifted up by 7 are unlocked.","isCorrect":false}],"answer":"Every reachable sum stays, and each one plus the stone becomes reachable too. From {0, 2} the stone 7 unlocks 7 and 9, giving {0, 2, 7, 9}.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"transition-state","state":{"dp":[1,0,1,0,0,0,0,0,0,0,0,0],"i":2,"num":7}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Mark sum 0, then let each stone spread reachable group sums","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"dp":[1,0,0,0,0,0,0,0,0,0,0,0],"i":0}}]},"body":["The table holds group sums 0 through the half-target 11. Only sum 0 starts reachable, the rest empty.","Take the stones of [2, 7, 4, 1, 8, 1] one at a time. For each one, every sum already reachable stays, and that sum plus the stone becomes reachable too.","Watch the largest marked sum climb toward 11 as 2, then 7, then 4 are folded in, since that largest reachable half is what makes the leftover smallest."]},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Climb toward half","title":"Reach the closest half of [2, 7, 4, 1, 8, 1]","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"after-2","state":{"dp":[1,0,1,0,0,0,0,0,0,0,0,0],"i":2,"num":2}},{"id":"after-7","state":{"dp":[1,0,1,0,0,0,0,1,0,1,0,0],"i":9,"num":7}},{"id":"after-4","state":{"dp":[1,0,1,0,1,0,1,1,0,1,0,1],"i":11,"num":4}},{"id":"final","state":{"dp":[1,1,1,1,1,1,1,1,1,1,1,1],"i":11,"num":1}}]},"beats":[{"id":"after-2","title":"Folding in the first stone, 2. How far does the reachable run reach?","summary":"The table starts with only sum 0 reachable.","prompt":"The first stone, 2, is added to each sum already reachable.","options":[{"id":"zero-two","label":"Sums 0 and 2, nothing between them","rationale":"0 + 2 = 2 is the only new sum, and 0 stays reachable by leaving the 2 off. A lone 2 cannot make 1.","isCorrect":true},{"id":"up-to-two","label":"Sums 0, 1, and 2","rationale":"Sum 1 would need a stone of weight 1, which has not been placed yet. Only 0 + 2 = 2 is unlocked.","isCorrect":false},{"id":"only-two","label":"Only sum 2, sum 0 drops out","rationale":"Sum 0 never drops: leaving the 2 off still reaches it. So 0 stays reachable alongside the new 2.","isCorrect":false}],"answer":"Sums 0 and 2. The 2 lands on the reachable 0 to mark sum 2, and 0 stays reachable by skipping it, so the run is {0, 2}."},{"id":"after-7","title":"After folding in the 7, what is the largest sum reachable so far?","summary":"Reachable before the 7: {0, 2}. The half-target is 11.","prompt":"The stone 7 is added to each sum already reachable.","options":[{"id":"nine","label":"9, from 2 + 7","rationale":"2 was reachable, so 2 + 7 = 9 is the highest new sum at or below 11. The set becomes {0, 2, 7, 9}, and 9 is the closest to half yet.","isCorrect":true},{"id":"seven","label":"7, since the stone is 7","rationale":"7 is reachable, but 2 + 7 = 9 reaches higher and still sits under 11. The largest is 9, not 7.","isCorrect":false},{"id":"eleven","label":"11, the target is already hit","rationale":"Reaching 11 would need 4 + 7, but 4 is not reachable yet. The highest so far is 9.","isCorrect":false}],"answer":"9, from 2 + 7. The reachable set is {0, 2, 7, 9}, so the closest sum to half is 9, two short of the target 11."},{"id":"after-4","title":"The 4 is folded in next. Does any group sum reach the target 11?","summary":"Reachable before the 4: {0, 2, 7, 9}. The target is 11.","prompt":"The stone 4 is added to each sum already reachable.","options":[{"id":"yes-from-seven","label":"Yes, because 7 was reachable and 7 + 4 = 11","rationale":"7 was reachable, so adding the 4 marks 11. One group can weigh exactly 11, leaving the other at 12.","isCorrect":true},{"id":"no-overshoot","label":"No, 9 + 4 = 13 overshoots the target","rationale":"13 is past 11 and is ignored, but 7 + 4 = 11 lands exactly on the target. The hit comes from 7, not 9.","isCorrect":false},{"id":"no-too-small","label":"No, the 4 only reaches up to 4","rationale":"The 4 can be added to any reachable sum. Adding it to the reachable 7 makes 11.","isCorrect":false}],"answer":"Yes. 7 was reachable, so 7 + 4 = 11 marks the target. The best reachable half is now 11."},{"id":"final","title":"Every stone has been folded in. What does the function return?","summary":"The remaining 1, 8, and 1 only fill gaps; the best reachable half is already 11.","prompt":"The best reachable group sum at or below 11 is 11, and the total is 23.","options":[{"id":"one","label":"1, the gap between the two groups","rationale":"One group weighs 11 and the other weighs 23 - 11 = 12, so the smallest leftover is 12 - 11 = 1, which is 23 - 2 * 11.","isCorrect":true},{"id":"eleven","label":"11, the best reachable half","rationale":"11 is one group's weight. The leftover is the gap to the other group, 23 - 2 * 11 = 1.","isCorrect":false},{"id":"twelve","label":"12, the heavier group's weight","rationale":"12 is the other group's weight. Smashing reduces the two groups to their gap, 12 - 11 = 1.","isCorrect":false}],"answer":"1. The best reachable half is 11, the other group is 12, and the leftover is their gap, 23 - 2 * 11 = 1."}]},{"id":"forward-order-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Can the sums update from low to high?","summary":"Sweeping each stone across sums from low to high feels just as natural, and the same sums seem to get marked. But the direction of the sweep quietly changes what a half-built cell is allowed to mean during one stone's pass. Watch what that lets a single stone do.","workspacePanel":"trace","pitfall":"The code below updates sums from low to high for each stone instead of from high to low.","whyItMatters":"On stones = [1, 3] with half-target 2, the low-to-high sweep marks sum 1 from the single 1, then immediately reads that fresh sum 1 to mark sum 2, spending the one 1 twice. It records best = 2 and returns 4 - 2 * 2 = 0, but no group of {1, 3} sums to 2, so the true leftover is 2. Sweeping sums from high to low reads only values from before this stone, so each stone is used at most once.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def lastStoneWeightII(stones: list[int]) -> int:\n    total = sum(stones)\n    target = total // 2\n    dp: list[bool] = [False] * (target + 1)\n    dp[0] = True\n    best = 0\n    for stone in stones:\n        for w in range(stone, target + 1):\n            if dp[w - stone]:\n                dp[w] = True\n                best = max(best, w)\n    return total - 2 * best","steps":[{"id":"start","title":"Start with only sum 0 reachable, target 2","codeLine":4,"summary":"stones = [1, 3], total = 4, target = 2. The table marks sum 0 reachable and the rest empty.","state":{"dp":[1,0,0],"i":0,"labels":{"i":"w"}}},{"id":"mark-one","title":"The stone 1 marks sum 1","codeLine":10,"summary":"Sweeping low to high, w = 1 reads dp[0] and marks sum 1 reachable.","state":{"dp":[1,1,0],"i":1,"labels":{"i":"w"}}},{"id":"reuse-one","title":"The same pass moves on to sum 2","codeLine":8,"summary":"Still on the stone 1, the inner sweep advances to w = 2, about to read dp[1], which was just set this pass.","state":{"dp":[1,1,0],"i":2,"labels":{"i":"w"}}},{"id":"reuse-mark","title":"It marks sum 2 by adding the same 1 again","codeLine":10,"summary":"w = 2 reads the fresh dp[1] and marks sum 2, spending the one 1 a second time within this pass, so best climbs to 2.","state":{"dp":[1,1,1],"i":2,"labels":{"i":"w"}}},{"id":"wrong-zero","title":"It returns 0 for an impossible split","codeLine":12,"summary":"best = 2 gives 4 - 2 * 2 = 0, yet {1, 3} has no group summing to 2. The single 1 was counted twice, so the leftover should be 2.","state":{"dp":[1,1,1],"i":2,"labels":{"i":"w"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const total = stones.reduce((total, value) => total + value, 0);\nconst target = Math.floor(total / 2);\nconst dp = Array((target + 1)).fill(false);\ndp[0] = true;\nlet best = 0;\nfor (const stone of stones) {\n    for (let w = stone; w < (target + 1); w++) {\n        if (dp[(w - stone)]) {\n            dp[w] = true;\n            best = Math.max(best, w);\n        }\n    }\n}\nreturn (total - (2 * best));","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const total = stones.reduce((total, value) => total + value, 0);\nconst target = Math.floor(total / 2);\nconst dp = Array((target + 1)).fill(false);\ndp[0] = true;\nlet best = 0;\nfor (const stone of stones) {\n    for (let w = stone; w < (target + 1); w++) {\n        if (dp[(w - stone)]) {\n            dp[w] = true;\n            best = Math.max(best, w);\n        }\n    }\n}\nreturn (total - (2 * best));","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int total = stones.stream().mapToInt(Integer::intValue).sum();\nint target = Math.floorDiv(total, 2);\nList<Boolean> dp = new ArrayList<>();\nfor (int index = 0; index < (target + 1); index++) {\n    dp.add(false);\n}\ndp.set(0, true);\nint best = 0;\nfor (Integer stone : stones) {\n    for (int w = stone; w < (target + 1); w++) {\n        if (dp.get(w - stone)) {\n            dp.set(w, true);\n            best = Math.max(best, w);\n        }\n    }\n}\nreturn (total - (2 * best));","lineMap":{"2":1,"3":2,"4":3,"5":7,"6":8,"7":9,"8":10,"9":11,"10":12,"11":13,"12":17},"statementBundles":{"4":{"startLine":3,"endLine":6},"11":{"startLine":13,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int total = stones.Sum();\nint target = total / 2;\nList<bool> dp = Enumerable.Repeat<bool>(false, target + 1).ToList();\ndp[0] = true;\nint best = 0;\nforeach (int stone in stones) {\n    for (int w = stone; w < target + 1; w++) {\n        if (dp[w - stone]) {\n            dp[w] = true;\n            best = Math.Max(best, w);\n        }\n    }\n}\nreturn total - 2 * best;","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int total = accumulate(stones.begin(), stones.end(), 0);\nint target = total / 2;\nvector<bool> dp = vector<bool>((target + 1), false);\ndp[0] = true;\nint best = 0;\nfor (int stone : stones) {\n    for (int w = stone; w < (target + 1); w++) {\n        if (dp[(w - stone)]) {\n            dp[w] = true;\n            best = max(best, w);\n        }\n    }\n}\nreturn (total - (2 * best));","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":10,"12":14},"statementBundles":{"11":{"startLine":10,"endLine":13}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"arrays":[{"name":"one stone","values":[7]},{"name":"even split","values":[1,1,4,2,2]},{"name":"odd total","values":[1,1,1]}]}}]},"body":["Spreading reachable group sums outward from 0, one stone at a time, raised the best reachable half whenever a subset could climb higher toward the target.","A lone stone with no partner, a set that splits into two equal halves, and an odd total that can never split evenly each lean on the rule differently. Run it on stones = [7], then stones = [1, 1, 4, 2, 2], then stones = [1, 1, 1]."]},{"id":"single-stone-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What is left when there is only one stone?","summary":"stones = [7], with total 7 and half-target 3.","workspacePanel":"visualizer","options":[{"id":"stone-itself","label":"7, the stone is left untouched","rationale":"With no partner, the best reachable group sum at or below 3 is 0, so the leftover is 7 - 2 * 0 = 7. The lone stone stays whole, and no special branch is needed.","isCorrect":true},{"id":"zero","label":"0, a single stone cancels itself","rationale":"A stone needs a partner to smash, and there is none. The group sum stays 0, so the whole 7 remains.","isCorrect":false},{"id":"three","label":"3, the half-target","rationale":"The half-target only bounds the search; it is not the answer. No subset of [7] reaches 3, so the best half is 0 and the leftover is 7.","isCorrect":false}],"answer":"7. The 7 is too big for the half-target 3, so the best reachable half stays 0 and the leftover is 7 - 2 * 0 = 7. The same DP returns it with no extra case.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"nums":[7],"total":7,"target":3,"labels":{"nums":"stones"}}}]}},{"id":"perfect-split-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"Can the leftover reach 0?","summary":"stones = [1, 1, 4, 2, 2], with total 10 and half-target 5.","workspacePanel":"visualizer","options":[{"id":"yes-zero","label":"Yes, because a group reaches exactly 5","rationale":"[1, 2, 2] sums to 5, so the best reachable half is the target 5 itself. The leftover is 10 - 2 * 5 = 0, an even split.","isCorrect":true},{"id":"no-positive","label":"No, a leftover stone always remains","rationale":"When a group hits exactly half, both groups weigh the same and destroy each other. Here 5 is reachable, so the leftover is 0.","isCorrect":false},{"id":"two","label":"2, the largest stone","rationale":"The largest stone does not bound the leftover. A subset reaches the half-target 5, so the groups balance at 5 and 5 and the leftover is 0.","isCorrect":false}],"answer":"Yes, 0. A subset reaches the half-target 5, so both groups weigh 5 and cancel, leaving 10 - 2 * 5 = 0. The DP returns 0 because the target cell becomes reachable.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"perfect-state","state":{"dp":[1,1,1,1,1,1],"i":5}}]}},{"id":"odd-total-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What happens when the total is odd?","summary":"stones = [1, 1, 1], with total 3 and half-target 1.","workspacePanel":"visualizer","options":[{"id":"at-least-one","label":"The leftover is at least 1, and the DP still floors the target","rationale":"An odd total can never split evenly, so the gap is at least 1. The best reachable half is 1, giving 3 - 2 * 1 = 1, with no parity branch needed.","isCorrect":true},{"id":"zero","label":"0, the stones can still balance","rationale":"Three identical stones cannot form two equal whole groups out of an odd total. The closest split is 1 and 2, leaving 1.","isCorrect":false},{"id":"round-up","label":"Round the target up to 2 to balance better","rationale":"Rounding the target up would search a sum the group can never owe; flooring to 1 keeps it honest. The best reachable half is 1, so the leftover is 1.","isCorrect":false}],"answer":"The leftover is at least 1. With total 3 the floored half-target is 1, a group reaches 1, and the leftover is 3 - 2 * 1 = 1. Flooring the target keeps the search valid.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"odd-state","state":{"nums":[1,1,1],"total":3,"target":1,"labels":{"nums":"stones"}}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Sweep each stone across sums from high to low, so no stone is spent twice.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"dp":[1,0,0,0,0,0,0,0,0,0,0,0],"i":0}}]},"body":["Sum the stones and aim for half that total, then build a reachability table over group sums 0 through the half-target, with only sum 0 marked at the start.","Fold in one stone at a time, marking each sum it can newly reach and remembering the largest reachable half, then turn that best half into the leftover gap."]},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the rule","title":"Build the closest-half reachability table","summary":"Now build it: sum the stones and halve that for the target, allocate the reachability table over sums 0 through the target and seed sum 0, then sweep each stone from the target down to its weight, tracking the largest reachable half as you go and returning the total minus twice it.","workspacePanel":"code","checkpoints":[{"id":"calculate-total","title":"Compute total weight","description":"Sum all stone weights so the problem can be reframed as a split.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_input_aggregate","scope":"calculate-total","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Compute the total weight across all stones.","doneWhen":"This step is done when the code derives a total from the input stones before creating the DP table.","shouldFailWhen":"This step should fail if the total is hard-coded or does not aggregate the input stones.","roles":["stones","total weight","group difference"],"mustProve":["The code aggregates all input stone weights.","The aggregate is available before the subset target is computed."],"mustNotAccept":["Using only the largest stone as the total.","Skipping the total and simulating greedy smashes."],"equivalentVariants":["Use sum(stones).","Use a loop that accumulates every stone weight."],"proofSnippets":[{"id":"py-last-stone-ii-calculate-total","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        return 0"}]},"commonMistakes":["Trying to model the smash operations directly","Using only part of the array when computing total"],"hint":"The final weight is the difference between two group sums, so first compute their combined sum."},{"id":"calculate-target","title":"Target half the total","description":"Compute the largest subset sum we need to consider.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_half_total_target","scope":"calculate-target","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Limit the subset-sum search to half of the total weight.","doneWhen":"This step is done when the code derives target = total // 2 or an equivalent half-total capacity.","shouldFailWhen":"This step should fail if the target is unrelated to total or if it searches all sums unnecessarily.","roles":["total weight","half capacity","closest subset"],"mustProve":["The target is derived from the total weight.","The target represents the half-sum boundary."],"mustNotAccept":["Using max(stones) as the target.","Using the full total as the DP capacity."],"equivalentVariants":["Use total // 2.","Use floor(total / 2) in another language."],"proofSnippets":[{"id":"py-last-stone-ii-calculate-target","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        return 0"}]},"commonMistakes":["Targeting the full total instead of half","Forgetting that a subset above half has a mirrored complement below half"],"hint":"The closer one group is to total // 2, the smaller the final difference becomes."},{"id":"init-dp","title":"Create reachable-sum table","description":"Allocate a boolean table for sums from 0 through target.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_boolean_subset_table","scope":"init-dp-array","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Create a boolean DP table where dp[w] means some processed subset can sum to w.","doneWhen":"This step is done when the code allocates target + 1 boolean cells before processing stones.","shouldFailWhen":"This step should fail if the table is missing, numeric counts are used for the wrong recurrence, or the capacity is too small.","roles":["boolean DP table","reachable sum","target capacity"],"mustProve":["The table covers every capacity from 0 through target.","The table is initialized before any stone transitions."],"mustNotAccept":["Using a scalar best value without reachable state.","Allocating only target cells and missing index target."],"equivalentVariants":["Use a boolean list of length target + 1.","Use an equivalent indexed reachable-state table."],"proofSnippets":[{"id":"py-last-stone-ii-init-dp","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        return 0"}]},"commonMistakes":["Allocating a table up to total instead of target","Forgetting that index target must be included"],"hint":"Each index in dp is a possible subset weight."},{"id":"set-base-case","title":"Seed sum zero","description":"Mark sum 0 as reachable before using any stones.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"sets_zero_subset_base_case","scope":"set-base-case","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Represent the empty subset as a reachable sum of zero.","doneWhen":"This step is done when dp[0] is set to true before the nested loops.","shouldFailWhen":"This step should fail if dp[0] remains false or if the base case is set after transitions.","roles":["empty subset","zero sum","base cell"],"mustProve":["The zero-sum cell is marked reachable.","The base case is established before processing stones."],"mustNotAccept":["Seeding dp[target] instead of dp[0].","Skipping the base case and relying on accidental truthy values."],"equivalentVariants":["Set dp[0] to True.","Use an equivalent boolean reachable-state seed at sum zero."],"proofSnippets":[{"id":"py-last-stone-ii-set-base-case","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        return 0"}]},"commonMistakes":["Forgetting that the empty subset is needed to start transitions","Setting the wrong DP index to true"],"hint":"Before picking any stones, sum 0 is reachable."},{"id":"backward-transition","title":"Run backward subset transitions","description":"For each stone, update reachable weights from target down to the stone weight.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"uses_backward_subset_transition","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Use each stone at most once while updating reachable subset sums.","doneWhen":"This step is done when every stone drives a descending capacity loop and dp[weight] considers dp[weight - stone].","shouldFailWhen":"This step should fail if the capacity loop runs forward or if the recurrence can reuse a stone in the same pass.","roles":["current stone","descending capacity","previous reachable sum"],"mustProve":["Each stone is processed in an outer loop.","The inner capacity loop moves downward from target to the current stone."],"mustNotAccept":["Iterating capacities upward.","Updating dp[weight] without referencing dp[weight - stone]."],"equivalentVariants":["Use range(target, stone - 1, -1).","Use any descending loop shape that preserves 0/1 single-use behavior."],"proofSnippets":[{"id":"py-last-stone-ii-backward-transition","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        for stone in stones:\n            for weight in range(target, stone - 1, -1):\n                dp[weight] = dp[weight] or dp[weight - stone]\n        return 0"}]},"commonMistakes":["Looping weight upward and using a stone more than once","Checking dp[stone - weight] instead of dp[weight - stone]"],"hint":"Backward capacity order is what makes this 0/1 knapsack instead of unbounded knapsack."},{"id":"track-best","title":"Track the closest reachable half","description":"Remember the largest reachable subset sum that does not exceed target.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Maintain the best reachable weight seen so far during the DP traversal.","doneWhen":"This step is done when the code updates a numeric best state from a reachable capacity.","shouldFailWhen":"This step should fail if the best value is never updated or if it ignores reachability.","roles":["best reachable weight","current capacity","reachable state"],"mustProve":["The code tracks a numeric maximum.","The maximum is updated from a capacity that the DP has marked reachable."],"mustNotAccept":["Returning the largest stone weight.","Updating best without checking reachability."],"equivalentVariants":["Use best = max(best, weight) when dp[weight] is reachable.","Track the same maximum reachable capacity through an equivalent numeric state."],"proofSnippets":[{"id":"py-last-stone-ii-track-best","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        best = 0\n        for stone in stones:\n            for weight in range(target, stone - 1, -1):\n                dp[weight] = dp[weight] or dp[weight - stone]\n                if dp[weight]:\n                    best = max(best, weight)\n        return 0"}]},"commonMistakes":["Tracking the first reachable weight instead of the largest","Updating best before dp[weight] has been updated"],"hint":"The closest split is the maximum reachable weight at or below target."},{"id":"return-difference","title":"Return the minimum difference","description":"Convert the best half-sum into the final stone weight.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_difference_between_numeric_states","scope":"compute-gap","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the difference between the total weight and twice the best reachable half-sum.","doneWhen":"This step is done when the code returns total - 2 * best or an equivalent group-sum difference.","shouldFailWhen":"This step should fail if the code returns best itself, target - best, or an unrelated DP cell.","roles":["total weight","best reachable half","minimum difference"],"mustProve":["The returned value combines total and the tracked best reachable half.","The formula represents the difference between the two group sums."],"mustNotAccept":["Returning best instead of the leftover difference.","Returning total - best instead of total - 2 * best."],"equivalentVariants":["Return total - 2 * best.","Return abs((total - best) - best)."],"proofSnippets":[{"id":"py-last-stone-ii-return-difference","language":"python","code":"class Solution:\n    def lastStoneWeightII(self, stones: list[int]) -> int:\n        total = sum(stones)\n        target = total // 2\n        dp = [False] * (target + 1)\n        dp[0] = True\n        best = 0\n        for stone in stones:\n            for weight in range(target, stone - 1, -1):\n                dp[weight] = dp[weight] or dp[weight - stone]\n                if dp[weight]:\n                    best = max(best, weight)\n        return total - 2 * best"}]},"commonMistakes":["Returning best instead of the final difference","Subtracting best only once from total"],"hint":"One group has weight best; the other has weight (total - best)."}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","body":["The smallest leftover is the gap between two stone groups, so push one group as close to half the total as a real subset allows.","Mark sum 0 reachable, fold each stone in by spreading reachability upward, track the largest reachable half, and return the total minus twice that half."],"takeaways":[{"title":"Smallest leftover is the closest half","body":"One group at the largest reachable sum below total / 2 leaves a gap of total - 2 * best, which is the smallest possible difference between the two groups."},{"title":"Sweep high to low for single use","body":"Each stone extends reachable sums, but updating from high to low reads only sums from before this stone, so no stone is counted twice."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
