forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimum_partition.py
More file actions
Latest commit
48 lines (36 loc) · 934 Bytes
/
Copy pathminimum_partition.py
File metadata and controls
48 lines (36 loc) · 934 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"""
Partition a set into two subsets such that the difference of subset sums is minimum
"""
deffind_min(arr: list[int]) ->int:
"""
>>> 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
"""
n=len(arr)
s=sum(arr)
dp= [[Falseforxinrange(s+1)] foryinrange(n+1)]
foriinrange(n+1):
dp[i][0] =True
foriinrange(1, s+1):
dp[0][i] =False
foriinrange(1, n+1):
forjinrange(1, s+1):
dp[i][j] =dp[i-1][j]
ifarr[i-1] <=j:
dp[i][j] =dp[i][j] ordp[i-1][j-arr[i-1]]
forjinrange(int(s/2), -1, -1):
ifdp[n][j] isTrue:
diff=s-2*j
break
returndiff
if__name__=="__main__":
fromdoctestimporttestmod
testmod()