Last Stone Weight II

Pattern: Subsequences and knapsack

medium

Smashing stones in any order amounts to giving each stone a + or - sign; the final weight is the absolute value of the signed sum. Make one group as close as possible to half the total: subset sum, then total - 2 × best.

The problem

Each turn, smash two stones of weights x ≤ y: equal stones both vanish, otherwise one stone of weight y - x remains. Return the smallest possible weight of the last stone (0 if none remain).

Think first

  • What does each stone contribute to the final weight?
  • So what are you really choosing?
  • What target makes the result smallest?

Hints

    Brute force, and why it fails

    Simulate every order of smashes: factorial.

    The key insight

    Every sign pattern can be reached by some order of smashes, so the problem is to split the stones into two piles as evenly as possible.

    Dry run

    half11

    stones [2, 7, 4, 1, 8, 1]: total 23, half 11.

    Step 1 of 3

    The plan

    can = subset sums up to total / 2
    best = largest reachable s <= total / 2
    return total - 2 × best
    

    Complexity

    Time
    O(n × total)
    Space
    O(total)

    Subset sum on half the total.

    Edge cases

    • One stone: its weight.
    • Two equal stones: 0.
    • All ones.
    I've built my logic, show the code

    Java

    class Solution {
        public int lastStoneWeightII(int[] stones) {
            int total = 0;
            for (int s : stones) total += s;
            boolean[] can = new boolean[total / 2 + 1];   // the stones split into two piles; make one as close to half as possible
            can[0] = true;
            for (int s : stones) for (int v = total / 2; v >= s; v--) if (can[v - s]) can[v] = true;
            for (int v = total / 2; v >= 0; v--) if (can[v]) return total - 2 * v;   // the difference of the two piles
            return total;
        }
    }

    C++

    class Solution {
    public:
        int lastStoneWeightII(vector<int>& stones) {
            int total = 0;
            for (int s : stones) total += s;
            vector<bool> can(total / 2 + 1, false); // split into two piles; make one as close to half as possible
            can[0] = true;
            for (int s : stones) for (int v = total / 2; v >= s; v--) if (can[v - s]) can[v] = true;
            for (int v = total / 2; v >= 0; v--) if (can[v]) return total - 2 * v;   // the difference of the two piles
            return total;
        }
    };

    Python

    class Solution:
        def lastStoneWeightII(self, stones: list[int]) -> int:
            total = sum(stones)
            reach = {0}                             # split into two piles; make one as close to half as possible
            for s in stones:
                reach |= {v + s for v in reach if v + s <= total // 2}
            return total - 2 * max(reach)           # the difference of the two piles

    Common mistakes

    • Simulating greedily with the two heaviest stones (that is Last Stone Weight I).
    • Searching above total / 2.

    Similar problems