2017-01-03 11:12:31 +00:00
|
|
|
"""
|
|
|
|
Partition a set into two subsets such that the difference of subset sums is minimum
|
|
|
|
"""
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
|
2023-10-13 17:48:31 +00:00
|
|
|
def find_min(numbers: list[int]) -> int:
|
2023-10-08 08:58:48 +00:00
|
|
|
"""
|
|
|
|
>>> find_min([1, 2, 3, 4, 5])
|
|
|
|
1
|
|
|
|
>>> find_min([5, 5, 5, 5, 5])
|
|
|
|
5
|
|
|
|
>>> find_min([5, 5, 5, 5])
|
|
|
|
0
|
|
|
|
>>> find_min([3])
|
|
|
|
3
|
|
|
|
>>> find_min([])
|
|
|
|
0
|
2023-10-13 17:48:31 +00:00
|
|
|
>>> find_min([1, 2, 3, 4])
|
|
|
|
0
|
|
|
|
>>> find_min([0, 0, 0, 0])
|
|
|
|
0
|
|
|
|
>>> find_min([-1, -5, 5, 1])
|
|
|
|
0
|
|
|
|
>>> find_min([-1, -5, 5, 1])
|
|
|
|
0
|
|
|
|
>>> find_min([9, 9, 9, 9, 9])
|
|
|
|
9
|
|
|
|
>>> find_min([1, 5, 10, 3])
|
|
|
|
1
|
|
|
|
>>> find_min([-1, 0, 1])
|
|
|
|
0
|
|
|
|
>>> find_min(range(10, 0, -1))
|
|
|
|
1
|
|
|
|
>>> find_min([-1])
|
|
|
|
Traceback (most recent call last):
|
|
|
|
--
|
|
|
|
IndexError: list assignment index out of range
|
|
|
|
>>> find_min([0, 0, 0, 1, 2, -4])
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
IndexError: list assignment index out of range
|
|
|
|
>>> find_min([-1, -5, -10, -3])
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
IndexError: list assignment index out of range
|
2023-10-08 08:58:48 +00:00
|
|
|
"""
|
2023-10-13 17:48:31 +00:00
|
|
|
n = len(numbers)
|
|
|
|
s = sum(numbers)
|
2017-01-03 11:12:31 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
dp = [[False for x in range(s + 1)] for y in range(n + 1)]
|
2017-01-03 11:12:31 +00:00
|
|
|
|
2023-10-08 08:58:48 +00:00
|
|
|
for i in range(n + 1):
|
2017-01-03 11:12:31 +00:00
|
|
|
dp[i][0] = True
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
for i in range(1, s + 1):
|
2017-01-03 11:12:31 +00:00
|
|
|
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):
|
2023-10-08 08:58:48 +00:00
|
|
|
dp[i][j] = dp[i - 1][j]
|
2017-01-03 11:12:31 +00:00
|
|
|
|
2023-10-13 17:48:31 +00:00
|
|
|
if numbers[i - 1] <= j:
|
|
|
|
dp[i][j] = dp[i][j] or dp[i - 1][j - numbers[i - 1]]
|
2017-01-03 11:12:31 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
for j in range(int(s / 2), -1, -1):
|
2020-05-22 06:10:11 +00:00
|
|
|
if dp[n][j] is True:
|
2019-10-05 05:14:13 +00:00
|
|
|
diff = s - 2 * j
|
|
|
|
break
|
2017-01-03 11:12:31 +00:00
|
|
|
|
|
|
|
return diff
|
2023-10-08 08:58:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
from doctest import testmod
|
|
|
|
|
|
|
|
testmod()
|