解法:简单背包题。
python
def solve(nums):
n = len(nums)
totalSum = sum(nums)
dp = [[False] * (totalSum // 2 + 1) for _ in range(n + 1)]
for i in range(n + 1):
dp[i][0] = True
for i in range(1, n + 1):
for j in range(1, totalSum // 2 + 1):
if nums[i - 1] <= j:
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]
else:
dp[i][j] = dp[i - 1][j]
minDiff = totalSum
for j in range(totalSum // 2, -1, -1):
if dp[n][j]:
minDiff = totalSum - 2 * j
break
return minDiff
if __name__ == "__main__":
n = int(input())
nums = list(map(int, input().split()))
result = solve(nums)
print(result)