forked from onlybooks/python-algorithm-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23-zero-one-knapsack.py
More file actions
31 lines (26 loc) · 667 Bytes
/
23-zero-one-knapsack.py
File metadata and controls
31 lines (26 loc) · 667 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
cargo = [
(4, 12),
(2, 1),
(10, 4),
(1, 1),
(2, 2),
]
def zero_one_knapsack(cargo):
capacity = 15
pack = []
for i in range(len(cargo) + 1):
pack.append([])
for c in range(capacity + 1):
if i == 0 or c == 0:
pack[i].append(0)
elif cargo[i - 1][1] <= c:
pack[i].append(
max(
cargo[i - 1][0] + pack[i - 1][c - cargo[i - 1][1]],
pack[i - 1][c]
))
else:
pack[i].append(pack[i - 1][c])
return pack[-1][-1]
r = zero_one_knapsack(cargo)
print(r)