Python/dynamic_programming/minimum_partition.py

31 lines
655 B
Python
Raw Normal View History

"""
Partition a set into two subsets such that the difference of subset sums is minimum
"""
2019-10-05 05:14:13 +00:00
def find_min(arr):
n = len(arr)
s = sum(arr)
2019-10-05 05:14:13 +00:00
dp = [[False for x in range(s + 1)] for y in range(n + 1)]
2019-10-05 05:14:13 +00:00
for i in range(1, n + 1):
dp[i][0] = True
2019-10-05 05:14:13 +00:00
for i in range(1, s + 1):
dp[0][i] = False
2019-10-05 05:14:13 +00:00
for i in range(1, n + 1):
for j in range(1, s + 1):
dp[i][j] = dp[i][j - 1]
2019-10-05 05:14:13 +00:00
if arr[i - 1] <= j:
dp[i][j] = dp[i][j] or dp[i - 1][j - arr[i - 1]]
2019-10-05 05:14:13 +00:00
for j in range(int(s / 2), -1, -1):
if dp[n][j] is True:
2019-10-05 05:14:13 +00:00
diff = s - 2 * j
break
return diff