Dynamic programming can run in time O(numItems * knapsackCapacity)
and O(knapsackCapacity)
memory. This means that, for your specifications, you would have:
- about
20.000.000 x 500 = 10.000.000.000
operations - would probably finish executing in a few hours, depending on your machine;
- since the profit of one item is at most 10 and you can have at most 500 items, that means your maximum theoretical profit cannot exceed
10 x 500 = 5000
. This can be represented on 2 bytes (a short). So you will also need 2 x 20.000.000 / 1024 / 1024 ~= 38 MB
of memory to store your DP array. Again, not that much.
The others have already mentioned the advantages and disadvantages of each. GA will finish faster, but the DP solution should also finish in a few hours, and it will give you an exact answer.
Personally, I would choose DP if waiting a few hours for the solution is not a problem.
Note: here is the DP that runs with O(knapsackCapacity)
memory:
dp[i] = maximum profit obtainable for weight i
for i = 1 to numItems do
for j = knapsackCapacity down to items[i].weight do
dp[j] = max(dp[j], dp[j - items[i].weight] + items[i].profit)