Last Stone Weight II LeetCode solution in Python
1class Solution:2def lastStoneWeightII(self, stones: List[int]) -> int:3if len(stones) == 1:4return stones[0]5total = sum(stones)6half, leng = total // 2, len(stones)7dp = [[0] * (half + 1) for _ in range(leng + 1)]89for i in range(1, leng + 1):10for j in range(1, half + 1):11if j - stones[i - 1] >= 0:12dp[i][j] = max(13dp[i - 1][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]14)15else:16dp[i][j] = dp[i - 1][j]17return total - 2 * dp[leng][half]