Last Stone Weight II

medium dp knapsack

Problem

You may smash stones pairwise with optimal pairing. The minimum possible final weight equals |sum1 − sum2| where the stones are partitioned into two subsets. To minimize that, find the largest subset sum ≤ total/2; the answer is total − 2·bestSum.

Inputstones = [2, 7, 4, 1, 8, 1]
Output1
Total = 23, target = 11. Best subset {1,2,8} sums to 11. Answer = 23 − 22 = 1.

def last_stone_weight_ii(stones):
    total = sum(stones)
    target = total // 2
    dp = [False] * (target + 1)
    dp[0] = True
    for s in stones:
        for j in range(target, s - 1, -1):
            dp[j] = dp[j] or dp[j - s]
    for j in range(target, -1, -1):
        if dp[j]:
            return total - 2 * j
function lastStoneWeightII(stones) {
  const total = stones.reduce((a, b) => a + b, 0);
  const target = total >> 1;
  const dp = new Array(target + 1).fill(false);
  dp[0] = true;
  for (const s of stones) {
    for (let j = target; j >= s; j--) {
      if (dp[j - s]) dp[j] = true;
    }
  }
  for (let j = target; j >= 0; j--) if (dp[j]) return total - 2 * j;
}
class Solution {
    public int lastStoneWeightII(int[] stones) {
        int total = 0;
        for (int s : stones) total += s;
        int target = total / 2;
        boolean[] dp = new boolean[target + 1];
        dp[0] = true;
        for (int s : stones) {
            for (int j = target; j >= s; j--) {
                if (dp[j - s]) dp[j] = true;
            }
        }
        for (int j = target; j >= 0; j--) if (dp[j]) return total - 2 * j;
        return 0;
    }
}
int lastStoneWeightII(vector<int>& stones) {
    int total = 0;
    for (int s : stones) total += s;
    int target = total / 2;
    vector<bool> dp(target + 1, false);
    dp[0] = true;
    for (int s : stones) {
        for (int j = target; j >= s; j--) {
            if (dp[j - s]) dp[j] = true;
        }
    }
    for (int j = target; j >= 0; j--) if (dp[j]) return total - 2 * j;
    return 0;
}
Time: O(n·S) Space: O(S)