Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to sort inputs for dynamic programming knapsack

In every single example I've found for a 1/0 Knapsack problem using dynamic programming where the items have weights(costs) and profits, it never explicitly says to sort the items list, but in all the examples they are sorted by increasing both weight and profit (higher weights have higher profits in the examples). So my question is when adding items in the matrix from the item array/list, can I add them in any order, or do I add the one with the smallest weight or profit? Because from multiple examples I found I'm not sure if its just a coincidence or you do in fact need to put the smallest weight/profit into the matrix each time

like image 248
Tommy K Avatar asked Apr 24 '15 17:04

Tommy K


2 Answers

The dynamic programming solution is nothing but choosing all the possibilities (using brute force) in an efficient way (just by saving the values for future reference).

Note: We consider all the subsets. Even if the list is sorted or not the total number of subsets will be the same. So in the end all the subsets will get considered.

like image 183
Shubham Sharma Avatar answered Sep 25 '22 02:09

Shubham Sharma


No, you don't need to sort the weights because every row gives the maximum possible value under the weight limit of that row. The maximum will come in the last column of that row.

like image 40
Shruti Gupta Avatar answered Sep 24 '22 02:09

Shruti Gupta