Dynamic Programming Algorithm for 0-1 Knapsack Problem

We use the following data structures and variables:

n -- The number of items
W -- The capacity of the knapsack
v [n] -- An array that contains the profit for each individual item
w [n] -- An array that contains the weight for each individual item
P [n][W+1] -- The two-dimensional array we'll fill out to find the final solution

Algorithm

dp01knapsack (v, n, W, P)
{
    for (k = 0; k <= W; k++)
        P [0,k] = 0;

    for (i = 1; i <= n; i++)
    {
        P [i,0] = 0;

        for (k = 1; k <= W; k++)
        {
            if (w[i] <= k)
                P [i][k] = max (P [i-1][k], v [i] + P [i-1][k - w[i]])
            else
                P [i][k] = P [i-1][k]
        }
    }
}