is it possible to modify the 1-0 Knapsack algorithm to optimize the final total weight of items in the bags as first choice (and the values as second choice), maintaining the same algorithmic complexity?
I'm working on this java implementation (in the end of the article).
More specifically, I'm thinking of changing this piece of code
if (wt[item-1]<=weight){
V[item][weight]=Math.max (val[item-1]+V[item-1][weight-wt[item-1]], V[item-1][weight]);
}else{
V[item][weight]=V[item-1][weight];
}
with some other condition that firstly control if the weight is closer to the threshold adding this item and than, if the weight does not change, if the value is better.
Have you got an idea how to do this without change the complexity?
Thank you
EDIT with "firstly control if the weight is closer to the threshold adding this item" i mean reaching the weight limit of the backpack. In other words "maximizing the weight i can carry in my bag" without breaking it
Are you trying to do the following? Choose items so that the weight is maximized, while still respecting the weight limit. If there are multiple optimal solutions that each achieve the maximum possible weight, then choose among them by choosing the solution that has the largest total value.
If so, then I suggest the following. (I'm thinking about knapsack problem itself and not your Java implementation of it.)
Let
M
= the maximum value [edited] among all the items andN
= number of items. Replace each value (in the objective function) with weight + value/MN
.Then the model will maximize the total weight, while still respecting the weight limit. And if there are multiple solutions with the same optimal weight, it will choose the one with maximum value. Dividing by
MN
ensures that you'll never choose a solution with a better value at the expense of a worse weight.