Search code examples
dynamic-programmingknapsack-problemindices

Trouble with indices


I am writing a Maximum Value Knapsack algorithm. It takes in a Knapsack object with Items that have a value and cost. I declare a 2D array for calculating the max value. For the base cases I have set the zeroth row values to 0 and zeroth column values to 0. I am running into trouble when I grab an item in the knapsack because when I want to grab the zeroth item, I am really grabbing the first item in the knapsack and am consequently getting the wrong values in the 2D array. Can someone check out my code and see what I am missing?

public static double MaximumKnapsack(Knapsack knapsack) {
    int numItems = knapsack.getNumOfItems();
    int budget = (int) knapsack.getBudget();
    double[][] DP = new double[numItems+1][budget+1];

    boolean taken = false;
    for (int i = 0; i < numItems + 1; i++) {
        for (int b = 0; b < budget + 1; b++) {
            if (i == 0 || b == 0) {
                DP[i][b] = 0;
            }
            else
            {
                Item item = knapsack.getItem(i);
                if (item.getCost() > b) {
                    DP[i][b] = DP[i-1][b];
                }
                else
                {
                    DP[i][b] = Math.max(DP[i-1][b-(int) item.getCost()] + item.getValue(),
                                        DP[i-1][b]);
                    if (DP[i][b] == DP[i-1][b-(int) item.getCost()] + item.getValue() && item.getCost() != 0.0) {
                        taken = true;
                    }
                }
            }
        }
        taken = false;
    }
    return DP[numItems][budget];
}

Solution

  • I think the problem is in

    Item item = knapsack.getItem(i);
    

    beacuse your loop will start with i = 1. You should use:

    Item item = knapsack.getItem(i-1);