I am struggling to come up with a thorough algorithm to the following problem.
Similar to the original (or famous) 0-1 Knapsack problem, given a capacity, C, and items (v,w) where each item has a value, v, and a weight, w, we want to obtain the greatest possible sum of values such that the total weight of items in the knapsack will be <= C.
But we have only one constraint: - We can ONLY have an even number of items that go into the knapsack.
Same approach, same problem to solve, but this time, there can only be an even number of items that eventually maximize the value sum in the knapsack.
This is my general Java code approach for solving the answer, ignoring the constraint. Is there a way to evolve this solution given the constraint?
public static int max(int a, int b) {
return (a > b) ? a : b;
}
public static int knapSackMult(int capacity, Item[] items, int len,ArrayList<Item> bestItems){
int lookup[][] = new int[len + 1][capacity + 1]; //left column and top row all 0's
for (int row = 0; row <= len; row++){
for (int col = 0; col <= capacity; col++){
//base case
if (row == 0 || col == 0) {
lookup[row][col] = 0;
}
//if the current value's weight is <= current column (remember columns are from 0 to capacity so they indicate current weight
else if (items[row - 1].weight <= col) {
//will be the max of : 1) product of current value+above and left corresponding 2) one directly above
lookup[row][col] = max(items[row - 1].value + lookup[row - 1][col - items[row - 1].weight], lookup[row - 1][col]);
}
//otherwise just take the one above
else {
lookup[row][col] = lookup[row - 1][col];
}
}
}
int row = len;
int col = capacity;
while (row > 0) {
//if num above in LU is different than num
if (lookup[row][col] != lookup[row - 1][col]) {
//add it to our sumParts since we have a valid one
bestItems.add(items[row - 1]);
row--; //go up a row
col = col - items[row].weight; //go over current number in Array times
}
//otherwise go up a row
else {
row--;
}
}
return lookup[len][capacity];
}}
class Item {
public int weight;
public int value;
public Item(int w, int v){
this.weight = w;
this.value = v;
}}