29 lines
868 B
Python
29 lines
868 B
Python
toys_joy = [63, 12, 50, 100]
|
|
toys_space = [32, 8, 16, 40]
|
|
space_left = 64
|
|
|
|
num_toys = len(toys_joy)
|
|
# Initialise an empty table
|
|
table = [
|
|
[0 for x in range(space_left + 1)]
|
|
for x in range(num_toys + 1)
|
|
]
|
|
for i in range(num_toys + 1):
|
|
for j in range(space_left + 1):
|
|
# If we are out of space or toys we cannot choose a toy
|
|
if i == 0 or j == 0:
|
|
table[i][j] = 0
|
|
# If there is space for the toy, then compare the joy of
|
|
# picking this toy over picking the next toy with more
|
|
# space left
|
|
elif toys_space[i - 1] <= j:
|
|
table[i][j] = max(
|
|
toys_joy[i - 1] + table[i - 1][j - wt[i - 1]],
|
|
table[i - 1][j],
|
|
)
|
|
# Otherwise, consider the next toy
|
|
else:
|
|
table[i][j] = table[i - 1][j]
|
|
|
|
optimal_joy = table[num_toys][space_left]
|